-
首先我們談談Event Loop:
setTimeout是一個macro任務
promise、和await後續爲micro任務
所以在執行順序上會先進行同步代碼,再者Promise、Async/Await,最好setTimeout。 -
談談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下面會不一樣,因爲機制不一樣;