談談setTimeout、Promise、Async/Await 的區別

  1. 首先我們談談Event Loop:
    setTimeout是一個macro任務
    promise、和await後續爲micro任務
    所以在執行順序上會先進行同步代碼,再者Promise、Async/Await,最好setTimeout。

  2. 談談Promise、Async/Await差異
    promise是resolve爲異步方法,將放入微任務隊裏裏執行,但是resolve前後的正常代碼爲同步代碼;Async/Await會返回一個promise,await 的順序是從右往左的,也就是說await 右邊的方法也優先執行同步代碼,再讓出線程,進入微任務隊列,await下面的代碼可以理解爲promise then裏面的代碼。
    下面是一個網上比較火的題:

 async function async1() {
        console.log( 'async1 start' )
        await async2()
        console.log( 'async1 end' )
    }
    
    async function async2() {
        console.log( 'async2' )
    }
    
    console.log( 'script start' )
    
    setTimeout( function () {
        console.log( 'setTimeout' )
    }, 0 )
    
    async1();
    
    new Promise( function ( resolve ) {
        console.log( 'promise1' )
        resolve();
    } ).then( function () {
        console.log( 'promise2' )
    } )
    
    console.log( 'script end' )

chrome下面的打印:具體可以仔細看看event loop的執行順序,當然node下面會不一樣,因爲機制不一樣;
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章