javascript - 在 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 3
?promise object
返回in.then
方法时发生了什么特别的事情?
解决方案
Javascript 运行一个事件循环。
这是我的猜测。
Promise.resolve()
创建一个将在下一次迭代中解决的承诺。并且每个 then 块将在前一个块完成后的下一次迭代中执行。所以这里是执行顺序:
迭代 1:创建了 2 个承诺(将它们命名为 A 和 B),它们将在迭代 2 中解决
迭代 2:Promise A 解决。承诺 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 的第三块执行,打印then
3。Promise C 的块执行,打印 4。
迭代 6:then
Promise B 的第四块执行,打印 5。
迭代 7:then
Promise B 的第五块执行,打印 6。
推荐阅读
- blockly - Blockly - build.py 在不同的计算机上没有产生一致的结果
- python-3.x - 将dict列表拆分为键列表、值列表
- vb.net - FieldQuoted 似乎无法正常工作
- mysql - SQLException:在 docker 中连接到 mysql 时访问被拒绝
- angular - Angular中的“ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改”错误
- python - 在 xonsh 中,我如何从管道接收到 python 表达式?
- javascript - 如何从 Bootstrap-Vue 重用项目提供程序功能更新 b 表中的项目异步?
- android - Android:按下按钮后如何让软键盘可见
- python - 如何检查闰年日期是否有效
- c - 如何在 Linux 上的 C 中复制时间属性?