嵌套 Promise 执行顺序

问题描述 投票:0回答:1

我正在阅读有关嵌套承诺的内容,并在教程中遇到了这种编码挑战。谁能解释一下这段代码的执行顺序吗?

new Promise((resolve) => {
    new Promise((res) => {
        console.log("c");
        resolve(3);
        res(2);
    }).then((response) => console.log(response))
}).then((res) => console.log(res));

我运行了代码,输出是:

c
2
3

但我期望输出应该是这样的:

c
3
2

因为先解决外部 Promise,然后再解决内部 Promise。

javascript reactjs asynchronous promise es6-promise
1个回答
0
投票

简而言之,就是因为你调用的顺序

.then

new Promise((resolve) => {
    new Promise((res) => {
        console.log("c");
        resolve(3);
        res(2);

在上面的代码中我们进入了外部构造函数,它立即调用了外部函数。然后我们进入内部构造函数,调用内部函数。这将外部 Promise 解析为 3,然后将内部 Promise 解析为 2。我们现在有两个已解析的 Promise。

}).then((response) => console.log(response))

接下来,我们对内部承诺进行链式

.then
调用。由于承诺已解决,这会将微任务排队运行。

}).then((res) => console.log(res));

接下来,我们对外部 Promise 进行链式

.then
调用。由于承诺已解决,这会将微任务排队运行。

现在我们已经完成了所有同步代码的运行。调用堆栈展开,微任务开始运行。第一个排队的微任务来自内部承诺,因此运行并注销 2。然后第二个微任务运行,并注销 3。

© www.soinside.com 2019 - 2024. All rights reserved.