实例分析js事件循环机制(2)

macro-task: script(整体代码), setTimeout, setInterval, setImmediate, I/O, UI rendering
micro-task: process.nextTick, Promises(这里指浏览器实现的原生 Promise), Object.observe, MutationObserver

结论

全部代码(script) macrotask -> microtask queue (含有promise.then) -> macrotask(setTimeout) -> 下一个microtask

Node.js的事件循环

process.nextTick & setImmediate

process.nextTick指定的任务总是发生在所有异步任务之前

setImmediate指定的任务总是在下一次Event Loop时执行

process.nextTick(function A() {
 console.log(1);
 process.nextTick(function B(){console.log(2);});
});
setTimeout(function timeout() {
 console.log('TIMEOUT FIRED');
}, 0)
new Promise(function(resolve) {
 console.log('glob1_promise');
 resolve();
}).then(function() {
 console.log('glob1_then')
})
process.nextTick(function() {
 console.log('glob1_nextTick');
})

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/957.html