setImmediate(function(){
console.log(1);
},0);
setTimeout(function(){
console.log(2);
},0);
new Promise(function(resolve){
console.log(3);
resolve();
console.log(4);
}).then(function(){
console.log(5);
});
console.log(6);
process.nextTick(function(){
console.log(7);
});
console.log(8);
結(jié)果是:3 4 6 8 7 5 2 1
事件的注冊(cè)順序如下:
setImmediate - setTimeout - promise.then - process.nextTick
因此篙螟,我們得到了優(yōu)先級(jí)關(guān)系如下:
process.nextTick > promise.then > setTimeout > setImmediate
至于為什么promise.then比setTimeout優(yōu)先執(zhí)行窘疮,原因如下:
Promise/A+規(guī)范指出:
Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such as setTimeout or setImmediate, or with a “micro-task” mechanism such as MutationObserver or process.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.
V8實(shí)現(xiàn)中,兩個(gè)隊(duì)列各包含不同的任務(wù):
macrotasks: script(整體代碼),setTimeout, setInterval, setImmediate, I/O, UI rendering
microtasks: process.nextTick, Promises, Object.observe, MutationObserver
執(zhí)行過(guò)程如下:
JavaScript引擎首先從macrotask queue中取出第一個(gè)任務(wù)俯萌,
執(zhí)行完畢后绍弟,將microtask queue中的所有任務(wù)取出技即,按順序全部執(zhí)行;
然后再?gòu)膍acrotask queue中取下一個(gè)樟遣,
執(zhí)行完畢后而叼,再次將microtask queue中的全部取出;
循環(huán)往復(fù)豹悬,直到兩個(gè)queue中的任務(wù)都取完葵陵。
解釋?zhuān)?/strong>
代碼開(kāi)始執(zhí)行時(shí),所有這些代碼在macrotask queue中瞻佛,取出來(lái)執(zhí)行之脱篙。
后面遇到了setTimeout
娇钱,又加入到macrotask queue中,
然后绊困,遇到了promise.then
文搂,放入到了另一個(gè)隊(duì)列microtask queue。
等整個(gè)execution context stack執(zhí)行完后秤朗,
下一步該取的是microtask queue中的任務(wù)了煤蹭。
因此promise.then
的回調(diào)比setTimeout
先執(zhí)行。