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')
})
})
执行逻辑
首先执行主线程任务 console.log(‘1’); 输出 1
遇到setTimeout 放进宏任务执行栈 标记为setTimeout 1
遇到 process.nextTick 放进微任务执行站 标记为process1
接着new Promise 直接执行 输出7 .then放进微任务 标记then1
最后一个setTimeout 放进宏任务执行栈 标记为setTimeout 2
第一轮主线程任务 执行完毕 输出 1 7
然后开始执行微任务 process1 输出 6
然后执行微任务 then1 输出 8
第一轮微任务执行完毕 此时输出 1 7 6 8
然后第二轮宏任务setTimeout 1开始执行
console.log(‘2’) 输出2
遇到process.nextTick 放进微任务 标记process2
遇到new Promise直接执行 输出 4
.then放进微任务 标记then2
setTimeout 1里面的宏任务执行完毕
开始执行微任务process2 输出 3
then2 输出 5
第二轮宏任务setTimeout 1执行完毕 输出 2 4 3 5
然后第三轮宏任务setTimeout 2同setTimeout 1 不在赘述
最后结果 输出 1 7 6 8 2 4 3 5 9 11 10 12