我很好奇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