宏任务 和 微任务都是异步任务
- 宏任务
setTimeout
setInterval - 微任务
process.nextTick()
promise.then() // 这个微任务一般放在nextTick队列后面如果异步队列里有nextTick队列的话
这道题帮助我们了解各种任务执行的顺序
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')
})
})
最终打印顺序是 1 7 6 8 2 4 3 5 9 11 10 12,你答对了吗