Promise和setTimeout執行順序


1、示例

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Promise和setTimeout執行順序 面試題</title>
    </head>

    <body>
        <script type="text/javascript">
            setTimeout(function() {
                console.log(1)
            }, 0);
            new Promise(function(a, b) {
                console.log(2);
                for(var i = 0; i < 10; i++) {
                    i == 9 && a();
                }
                console.log(3);
            }).then(function() {
                console.log(4)
            });
            console.log(5)
        </script>
    </body>

</html>
 

2、解釋

最需要 解釋的是:then和settimeout執行順序,即setTimeout(fn, 0)在下一輪“事件循環”開始時執行,Promise.then()在本輪“事件循環”結束時執行。因此then 函數先輸出,settimeout后輸出。先執行promise是宏任務隊列,而setTimeout是微任務隊列。

下面的輸出結果是多少

const promise = new Promise((resolve, reject) => { console.log(1); resolve(); console.log(2); }) promise.then(() => { console.log(3); }) console.log(4); 
Promise 新建后立即執行,所以會先輸出 1,2,而 Promise.then()內部的代碼在 當次 事件循環的 結尾 立刻執行 ,所以會繼續輸出4,最后輸出3

 3、自測題:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>js 執行順序</title>
    </head>

    <body>
        <script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
        <script type="text/javascript">
            console.log(1)
            setTimeout(function(){
                console.log(2);
                let promise = new Promise(function(resolve, reject) {
                      console.log(7);
                      resolve()
                }).then(function(){
                    console.log(8)
                });
            },1000);
            setTimeout(function(){
                console.log(10);
                let promise = new Promise(function(resolve, reject) {
                      console.log(11);
                      resolve()
                }).then(function(){
                    console.log(12)
                });
            },0);
            let promise = new Promise(function(resolve, reject) {
                  console.log(3);
                  resolve()
            }).then(function(){
                console.log(4)
            }).then(function(){
                console.log(9)
            });
            console.log(5)
        </script>
    </body>

</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM