promise封装setTimeout

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)

由于then在此代码中会先于setTimeout执行,于是就有了then和setTimeout的时序问题。和所写代码的目的不太一致,因为then是微任务。

promise和setTimeout共同使用时,要将setTimeout封装起来,就能避免类似问题。

全部评论

相关推荐

点赞 评论 收藏
分享
09-17 19:25
已编辑
太原理工大学 游戏测试
叁六玖:公司名发我,我要这个HR带我打瓦
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务