Promise.then 中的交替执行

606 阅读1分钟

结论

  • 如果有多个fulfilledPromise实例,同时执行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执行。