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
事件的注冊順序如下:
setImmediate - setTimeout - promise.then - process.nextTick
因此,我們得到了優(yōu)先級關(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實現(xiàn)中,兩個隊列各包含不同的任務(wù):
macrotasks: script(整體代碼),setTimeout, setInterval, setImmediate, I/O, UI rendering
microtasks: process.nextTick, Promises, Object.observe, MutationObserver
執(zhí)行過程如下:
JavaScript引擎首先從macrotask queue中取出第一個任務(wù),
執(zhí)行完畢后,將microtask queue中的所有任務(wù)取出,按順序全部執(zhí)行;
然后再從macrotask queue中取下一個,
執(zhí)行完畢后,再次將microtask queue中的全部取出;
循環(huán)往復(fù),直到兩個queue中的任務(wù)都取完。
解釋:
代碼開始執(zhí)行時,所有這些代碼在macrotask queue中,取出來執(zhí)行之。
后面遇到了setTimeout,又加入到macrotask queue中,
然后,遇到了promise.then,放入到了另一個隊列microtask queue。
等整個execution context stack執(zhí)行完后,
下一步該取的是microtask queue中的任務(wù)了。
因此promise.then的回調(diào)比setTimeout先執(zhí)行。