很好奇Event Loop和Promise的关系
该演示暴露了这个问题。我希望 p1 fulfilled
出现在中间,因为它们将任务排队到同一个任务队列并一个接一个地执行。
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不一样】 ,因为它更关注Event Loop和Promise之间的关系】
每个事件循环都有一个微任务队列和一个宏任务队列。
microtask 是本来要在microtask 队列而不是task 队列中排队的任务。引用https://www.w3.org/TR/html51/webappapis.html#microtask-queue .
有两种微任务:
- 单独的回调微任务,例如
Promise
,
- 和复合微任务,例如 Node.js 中的
Object.observe
、MutationObserver
和 process.nextTick
。
而宏任务队列主要包含setTimeout
、setInterval
、setImmediate
、requestAnimationFrame
、I/O
在 Nodejs 中。
在一个事件循环中,这两个任务队列会分两步运行:
- 首先检查旧的宏任务队列中是否有宏任务(称之为X);
- 如果X存在并且正在运行,等待它进入下一步,直到它完成;否则,立即进入下一步;
- 其次,运行微任务队列的所有微任务;
- 并且在运行微任务时,我们仍然可以在队列中添加更多的微任务,这些任务也会运行。
在你的例子中:
- 首先,你的Promise初始化
new Promise
和resolve
是同步的;
- 然后在宏任务队列中同步加入一个
setTimeout
宏任务;
- 然后同步添加微任务
promise.then(function(){})
到微任务队列,这个任务会立即运行,因为Promise初始化和解析是同步的,这个任务先于任何宏任务;所以,console.log p1 fulfilled
;
- 然后将第二个宏任务
setTimeout
添加到宏任务队列中;
- 在此事件循环结束后,运行两个宏任务;
对于这段代码:
setTimeout(function() {
console.log("will be executed at the top of the next Event Loop")
}, 0)
var p1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(1)
}, 0)
});
setTimeout(function() {
console.log("will be executed at the bottom of the next Event Loop")
}, 0)
for (var i = 0; i < 100; i++) {
(function(j) {
p1.then(function(value) {
console.log("promise then - " + j)
});
})(i)
}
输出顺序:
will be executed at the top of the next Event Loop
promise then - 0
promise then - 1
promise then - 2
...
promise then - 99
will be executed at the bottom of the next Event Loop
- 首先在宏任务队列中加入三个宏任务
setTimeout
,在微任务队列中加入一个微任务promise.then()
;
- 运行宏任务;
- 如果条件为真,则运行所有微任务,但为假,则进行下一步;
- 运行第二个宏任务;
- 检查promise是否解决,条件为真,然后运行所有微任务;
- 继续运行其他宏任务;