
new Promise(resolve => { console.log('promise'); resolve(5); }).then(value=>{ console.log('then回調', value) }) function func1() { console.log('func1'); } setTimeout(() => { console.log('setTimeout'); }); func1();
創建一個promise的實例就是開啟了一個異步任務,傳入的回調函數,也叫做excutor 函數,會立刻執行,所以輸入promise,使用resolve返回一個成功的執行結果,then函數里的執行會推入到微任務隊列中等待調用棧執行完成才依次執行。

setTimeout(function () { console.log("set1"); new Promise(function (resolve) { resolve(); }).then(function () { new Promise(function (resolve) { resolve(); }).then(function () { console.log("then4"); }); console.log("then2"); }); }); new Promise(function (resolve) { console.log("pr1"); resolve(); }).then(function () { console.log("then1"); }); setTimeout(function () { console.log("set2"); }); console.log(2); queueMicrotask(() => { console.log("queueMicrotask1") }); new Promise(function (resolve) { resolve(); }).then(function () { console.log("then3"); });
setTimeout執行的回調函數("set1")直接被放置到宏任務隊列中等待,Promise的excutor函數立刻執行,首先輸入 pr1,Promise.then函數("then1")放入微任務隊列中等待,下面的setTimeout執行的回調函數("set2")也被放置到宏任務隊列中,排在("set1")后面,接下來調用棧中輸出2,queueMicrotask表示開啟一個微任務,與Promise.then函數效果一致,("queueMicrotask1")放入微任務隊列中,再往下執行,new Promise的excutor函數立刻執行,then函數("then3")放到微任務隊列中等待,此時調用棧出已依次輸入pr1,2。
pr1 2 then1 queueMicrotask1 then3 set1 then2 then4 set2
簡單圖示如下
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')
函數只有調用的時候才會推入調用棧中,所以最先執行的是 console.log,即輸出 script start,然后setTimeout函數("setTimeout")放入宏任務隊列中等待,調用async1函數,輸出 async1 start,執行async2函數,輸出async2,("async1 end")放入微任務隊列中等待,繼續向下執行Promise函數,輸出 promise1,then函數中的("promise2")放入微任務隊列中等待,輸出 script end。
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
簡單圖示如下