首页 > 解决方案 > 在 promise then mehod 中返回 Promise 对象时的执行顺序

问题描述

代码是:

Promise.resolve().then(() => {
    console.log(0);
    return Promise.resolve(4);
}).then((res) => {
    console.log(res)
})

Promise.resolve().then(() => {
    console.log(1);
}).then(() => {
    console.log(2);
}).then(() => {
    console.log(3);
}).then(() => {
    console.log(5);
}).then(() =>{
    console.log(6);
})

结果是:0 1 2 3 4 5 6

为什么log 4 是后log 3promise object返回in.then方法时发生了什么特别的事情?

标签: javascriptpromise

解决方案


Javascript 运行一个事件循环。

这是我的猜测。

Promise.resolve()创建一个将在下一次迭代中解决的承诺。并且每个 then 块将在前一个块完成后的下一次迭代中执行。所以这里是执行顺序:

迭代 1:创建了 2 个承诺(将它们命名为 A 和 B),它们将在迭代 2 中解决

迭代 2:Promise A 解决。承诺 B 解决

迭代 3:thenPromise A 块执行,打印 0 并创建一个新的 Promise(命名为 C),它将在迭代 4 中解决then。Promise B 的第一个块执行,打印 1。

迭代 4:thenPromise B 的第二个块执行,打印 2. Promise C 解决。(由于 Promise C 比 Promise B 晚添加到事件循环中,所以 Promise B 在 Promise C 之前解析)

迭代 5:thenPromise B 的第三块执行,打印then3。Promise C 的块执行,打印 4。

迭代 6:thenPromise B 的第四块执行,打印 5。

迭代 7:thenPromise B 的第五块执行,打印 6。


推荐阅读