这里主要试分析一个面试题,然后总结一下答案
console.log('1');setTimeout(function() {console.log('2');process.nextTick(function() {console.log('3');})new Promise(function(resolve) {console.log('4');resolve();}).then(function() {console.log('5')})
})
process.nextTick(function() {console.log('6');
})
new Promise(function(resolve) {console.log('7');resolve();
}).then(function() {console.log('8')
})setTimeout(function() {console.log('9');process.nextTick(function() {console.log('10');})new Promise(function(resolve) {console.log('11');resolve();}).then(function() {console.log('12')})
})
首先记住一句话,在同一个时间循环中,微任务的优先级大于宏任务,在当前执行栈执行完毕时会立刻先处理所有微任务队列中的事件,然后再去宏任务队列中取出一个事件,只有前一个队列全部清空以后,才会执行下一个队列
Node 执行完所有同步任务,接下来就会执行process.nextTick的任务队列,如果你希望异步任务尽可能快地执行,那就使用 process.nextTick。
具体使用方法:
process.nextTick(() => console.log(3));
根据语言规格,Promise 对象的回调函数,会进入异步任务里面的”微任务”(microtask)队列。
微任务队列追加在 process.nextTick 队列的后面,也属于本轮循环。