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ù)都取完撕彤。
解釋:
代碼開始執(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í)行芳室。
作者:何幻
鏈接:http://www.reibang.com/p/3ed992529cfc
來(lái)源:簡(jiǎn)書
著作權(quán)歸作者所有专肪。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處堪侯。