gpt4 book ai didi

javascript - promise then方法中返回一个Promise对象时的执行顺序

转载 作者:行者123 更新时间:2023-12-04 13:24:55 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What happen when we return a value and when we return a Promise.resolve from a then() chain, in the microtask queue?

(2 个回答)



ES6 promise execution order for returned values

(2 个回答)



What is the difference between returned Promise?

(2 个回答)



What is the order of execution in JavaScript promises?

(3 个回答)


2个月前关闭。




代码是:

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 3 之后?返回 promise object 时发生了什么特别的事情在 .then方法?

最佳答案

Javascript 运行一个事件循环。
这是我的猜测。Promise.resolve()创建一个将在下一次迭代中解决的 promise 。并且每个 then 块将在上一个块完成后的下一次迭代中执行。所以这里是执行顺序:
迭代 1:创建了 2 个 promise (将它们命名为 A 和 B),它们将在迭代 2 中解决
迭代 2: promise A 解决。 promise B解决
迭代 3:then Promise A 块执行,打印 0 并创建一个新的 Promise(命名为 C),它将在迭代 4 中解决。第一个 then Promise B 的块执行,打印 1。
迭代 4:第二次 then Promise B 块执行,打印 2. Promise C 解析。 (由于 Promise C 是在 Promise B 之后加入事件循环的,所以 Promise B 在 Promise C 之前解析)
迭代 5:第三 then Promise B 块执行,打印 3。then执行 Promise C 块,打印 4。
迭代 6:第四 then Promise B 块执行,打印 5。
迭代 7:第五 then Promise B 块执行,打印 6。

关于javascript - promise then方法中返回一个Promise对象时的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69069149/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com