我很好奇Event Loop和Promise之间的关系。
该演示揭示了这个问题。我期望p1 fulfilled
出现在中间,
,因为他们排列任务到相同的任务队列,并逐一执行。
事件循环和Promise之间的关系
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
The visualized effect显示promise.then
的回调没有去到事件循环的任务队列。这是正确的?
【注:现在的问题是不一样的Promise vs setTimeout,因为它更注重事件循环和承诺之间的关系】
你可以想像,在当前[蜱]的端部(https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#处理的第二任务队列process-nexttick)即在正常任务队列中的任何事物之前。 – SpiderPig
'setTimeout'也有一个最小延迟。 – zzzzBov
_“我预计'p1 fulfilled'出现在中间。”_你为什么期待这样的结果? – guest271314