我们这篇主要讲浏览器和Nodejs环境下任务队列的执行顺序,尤其关注promise和async/await在任务队列中的执行顺序。
1.setTimeout、setImmediate、nextTick、Promise.next情况下
我们先记住几条结论:
1.有process和setImmediate就考虑是在nodejs环境下
2.微任务中nextTick队列在Promise.next前
3.宏任务中setTimeout在setImmediate前
4.所有可执行的微任务(包括nextTick和then)执行完毕之后,执行宏任务,注意宏任务队列并不是全部执行,执行全部的setTimeout队列中所有任务,再去执行对应产生的微任务,再去执行setImmediate,再去执行setImmediate产生的微任务。
我们先看一道题:
setTimeout(function(){
console.log(1)
},0);
new Promise(function(resolve,reject){
console.log(2);
resolve();
})
.then(function(){
console.log(3)
})
.then(function(){
console.log(4)
});
process.nextTick(function(){console.log(5)});
console.log(6);
输出2,6,5,3,4,1
参考文章:http://m.nowcod