关于JavaScript异步编程,前文解析过了JavaScript并发模型,该并发模型基于事件循环。正好在Stackoverflow上回答了一个关于setTimeout与Promise执行顺序相关的问题,于是总结这一知识点,与更多读者分享,同时完善JavaScript异步编程系列文章。
前言
我们先看一到常见的前端面试题:
var p1 = new Promise(function(resolve, reject){
resolve(1);
})
setTimeout(function(){
console.log("will be executed at the top of the next Event Loop");
},0)
p1.then(function(value){
console.log("p1 fulfilled");
})
setTimeout(function(){
console.log("will be executed at the bottom of the next Event Loop");
},0)
上例代码执行输出顺序如何?这道题也是本文创作的源泉,其答案是:
p1 fulfilled
will be executed at the top of the next Event Loop
will be executed at the bottom of the next Event Loop
接下来展开解释输出结果原因,看完本文应该能了解setTimeout和Prom