结论
-
如果有多个
fulfilled的Promise实例,同时执行then链式调用,then会交替执行。 -
这是编译器的优化,防止一个
Promise占据过多时间。 -
在
then中返回Promise实例,会出现慢两拍的效果,具体表现为等待两个.then()执行完成。- 第一拍:
Promise需要等待pending变为fulfilled状态 - 第二拍:
then函数挂载到MicroTaskQueue中
- 第一拍:
// then 中无 返回 Promise 的情况
Promise.resolve().then(() => {
console.log(0); // 第1步
}).then(() => {
console.log(2); // 第3步
}).then(() => {
console.log(4); // 第5步
}).then(() => {
console.log(6); // 第7步
})
Promise.resolve().then(() => {
console.log(1); // 第2步
}).then(() => {
console.log(3); // 第4步
}).then(() => {
console.log(5); // 第6步
}).then(() => {
console.log(7); // 第8步
})
// 输出
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
Promise.resolve().then(() => {
console.log(0); // 第1步
// 等待两个 then 执行完成
return Promise.resolve(4)
}).then((res) => {
console.log(res); // 第5步
}).then(() => {
console.log(6); // 第7步
}).then(() => {
console.log(7); // 第8步
})
Promise.resolve().then(() => {
console.log(1); // 第2步
}).then(() => {
console.log(2); // 第3步
}).then(() => {
console.log(3); // 第4步
}).then(() => {
console.log(5); // 第6步
})
// 输出
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
不难发现,其实都是交替执行,只是在then中返回Promise的场景下,需要等待两个then执行。