这个 Promise 在 javascript 中是如何工作的
How is this Promise working in javascript
Promise
.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3));
Promise
.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6));
答案:1 4 2 5 3 6
有人可以向我解释一下它是如何工作的吗?
为什么不执行1,2,3,4,5,6
?
微任务中的一个.then
回调运行,当前运行ning同步代码仅运行一次完成。在这里,同步代码初始化了两个立即解析的 Promise,Promise.resolve
.
微任务按顺序解析,因此在脚本末尾,队列中有两个微任务:第一个放入队列的是 () => console.log(1)
,因此第一个被记录。此时,1
的 Promise 已解决,因此下一个 .then
(2
)被放入微任务队列。第二个被放入队列的是 () => console.log(4)
,因此第二个被记录,5
被放入微任务队列。然后 2
运行s 并将其下一个 .then
推入队列 (3),然后 4
运行s 并将其下一个 .then
( 6
) 到队列中。等等
// queue:
[1, 4]
// 1 gets logged
// 2 gets pushed
[4, 2]
// 4 gets logged
// 5 gets pushed
[2, 5]
// 2 gets logged
// 3 gets pushed
[5, 3]
...
如果您在继续第二个 Promise.resolve
之前等待第一个 Promise 的整个 Promise 链完全解决,那么它们都会 运行 按顺序排列,正如您所期望的那样:
(async () => {
await Promise
.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3));
await Promise
.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6));
})();
上述情况的发生是因为 .resolve().then( ...)
Promise 链构造的 Promise 只会在 final 链中的 Promise 解析后解析 - 即 [=27 之后=] 被记录。
Promise
.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3));
Promise
.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6));
答案:1 4 2 5 3 6
有人可以向我解释一下它是如何工作的吗?
为什么不执行1,2,3,4,5,6
?
微任务中的一个.then
回调运行,当前运行ning同步代码仅运行一次完成。在这里,同步代码初始化了两个立即解析的 Promise,Promise.resolve
.
微任务按顺序解析,因此在脚本末尾,队列中有两个微任务:第一个放入队列的是 () => console.log(1)
,因此第一个被记录。此时,1
的 Promise 已解决,因此下一个 .then
(2
)被放入微任务队列。第二个被放入队列的是 () => console.log(4)
,因此第二个被记录,5
被放入微任务队列。然后 2
运行s 并将其下一个 .then
推入队列 (3),然后 4
运行s 并将其下一个 .then
( 6
) 到队列中。等等
// queue:
[1, 4]
// 1 gets logged
// 2 gets pushed
[4, 2]
// 4 gets logged
// 5 gets pushed
[2, 5]
// 2 gets logged
// 3 gets pushed
[5, 3]
...
如果您在继续第二个 Promise.resolve
之前等待第一个 Promise 的整个 Promise 链完全解决,那么它们都会 运行 按顺序排列,正如您所期望的那样:
(async () => {
await Promise
.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3));
await Promise
.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6));
})();
上述情况的发生是因为 .resolve().then( ...)
Promise 链构造的 Promise 只会在 final 链中的 Promise 解析后解析 - 即 [=27 之后=] 被记录。