首先看下列代码的执行结果promise
console.log(1)
process.nextTick(function(){
console.log(2)
})
setTimeout(function(){
console.log(3)
process.nextTick(function(){
console.log(4)
})
})
Promise.resolve().then(function() {
console.log(5);
}).then(function() {
console.log(6)
});复制代码
同步任务、微任务、宏任务的执行优先级以下:浏览器
同步任务 > 微任务 > 宏任务复制代码
# | 浏览器 | Node |
---|---|---|
I/O |
✅ | ✅ |
setTimeout |
✅ | ✅ |
setInterval |
✅ | ✅ |
setImmediate |
❌ | ✅ |
requestAnimationFrame |
✅ | ❌ |
# | 浏览器 | Node |
---|---|---|
process.nextTick |
❌ | ✅ |
MutationObserver |
✅ | ❌ |
Promise.then catch finally |
✅ | ✅ |
回到题里面bash
一、第一行是同步任务,优先级最高,因此第一次输出1
二、后面有nextTick,是微任务,有promise是微任务,setTimeout是宏任务,因此setTimeouut里的代码最后执行
三、那就先依次执行微任务nextTick打印了2
四、接着执行另外一个微任务promise,打印了5,6
五、接着执行宏任务setTimeout,打印3
六、setTimeout里面有一个微任务,而后执行它,打印4复制代码
// 因此结果就是
1
2
5
6
3
4
复制代码