這道題主要考察的是事件循環中函數執行順序的問題,其中包括async
,await
,setTimeout
,Promise
函數。下面來講一下本題中涉及到的知識點。promise
//請寫出輸出內容 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'); /* script start async1 start async2 promise1 script end async1 end promise2 setTimeout */
首先咱們須要明白如下幾件事情:異步
任務隊列(task queue),一個任務隊列即是一系列有序任務(task)的集合;每一個任務都有一個任務源(task source),源自同一個任務源的 task 必須放到同一個任務隊列,從不一樣源來的則被添加到不一樣隊列。setTimeout/Promise 等API即是任務源,而進入任務隊列的是他們指定的具體執行任務。async
宏任務:(macro)task(又稱之爲宏任務)函數
微任務:microtask(又稱爲微任務)spa
運行:線程
https://www.ximalaya.com/yinyue/25395682/
https://www.ximalaya.com/yinyue/25395691/
https://www.ximalaya.com/yinyue/25371172/
https://www.ximalaya.com/yinyue/25371180/
https://www.ximalaya.com/yinyue/25371165/
https://www.ximalaya.com/yinyue/25371160/
https://www.ximalaya.com/yinyue/25371154/
https://www.ximalaya.com/yinyue/25371139/
https://www.ximalaya.com/yinyue/25371144/
https://www.ximalaya.com/yinyue/25371134/
https://www.ximalaya.com/yinyue/25371129/
https://www.ximalaya.com/yinyue/25371103/
https://www.ximalaya.com/yinyue/25371093/
https://www.ximalaya.com/yinyue/25371073/
https://www.ximalaya.com/yinyue/25371080/
https://www.ximalaya.com/yinyue/25371065/
https://www.ximalaya.com/yinyue/25371060/
https://www.ximalaya.com/yinyue/25371052/
https://www.ximalaya.com/yinyue/25371048/
https://www.ximalaya.com/yinyue/25371038/
https://www.ximalaya.com/yinyue/25371024/
https://www.ximalaya.com/yinyue/25370987/
https://www.ximalaya.com/yinyue/25370978/code