代码是:
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
.
Why log 4
是在之后log 3
?退货时发生了什么特别的事情promise object
in .then
method?
JavaScript 运行一个事件循环。
这是我的猜测。
Promise.resolve()
创建一个将在下一次迭代中解决的承诺。每个 then 块将在前一个块完成后的下一次迭代中执行。所以这是执行顺序:
迭代 1:创建 2 个 Promise(将其命名为 A 和 B),这将在迭代 2 中解决
迭代 2:Promise A 解决。 Promise B 解决了
迭代 3:then
Promise A 块执行,打印 0 并创建一个新的 Promise(将其命名为 C),该新 Promise 将在迭代 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。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)