【问题标题】:The execution sequence when returning a Promise object in promise then mehod [duplicate]在promise中返回Promise对象时的执行顺序然后方法[重复]
【发布时间】:2021-11-03 05:24:28
【问题描述】:

代码是:

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

【问题讨论】:

  • 请记住,这样的问题实际上只对求知欲有用。如果有真正的异步操作,并且您关心两个单独的 Promise 链中的相对执行顺序,那么您必须编写代码以按照您想要的方式控制顺序 - 您不依赖任何您将获得的东西这个问题的答案,因为它与真正的异步操作无关。
  • "在.then方法中返回promise对象时有什么特别的事情发生?"then()方法的回调函数的回调函数中返回promise then 方法返回的promise 解析为其回调函数返回的promise。见:MDN - then() Return Value
  • 虽然有这个问题的答案(与 Promises 的规范有关),但答案根本没有用。 不要依赖于该代码如何工作的知识。如果您很好奇,但随后完全忘记答案,那也没关系。取决于这样的事情是错误的来源。您需要编写异步代码以相互独立。如果它们是依赖的,则需要显式使其依赖(在 then(()=>console.log(3)) 中调用 resolve(4))

标签: javascript promise


【解决方案1】:

Javascript 运行一个事件循环。

这是我的猜测。

Promise.resolve() 创建一个将在下一次迭代中解决的承诺。并且每个 then 块将在前一个块完成后的下一次迭代中执行。所以这里是执行顺序:

迭代 1:创建了 2 个承诺(将它们命名为 A 和 B),它们将在迭代 2 中解决

迭代 2:Promise A 解决。承诺 B 解决

迭代 3:Promise A 的 then 块执行,打印 0 并创建一个新的 Promise(命名为 C),它将在迭代 4 中解决。Promise B 的第一个 then 块执行,打印 1 .

迭代 4:Promise B 的第二个 then 块执行,打印 2. Promise C 解析。 (由于 Promise C 比 Promise B 晚添加到事件循环中,所以 Promise B 在 Promise C 之前解析)

迭代 5:Promise B 的第三个 then 块执行,打印出 3。Promise C 的then 块执行,打印出 4。

迭代 6:Promise B 的第四个 then 块执行,打印 5。

迭代 7:Promise B 的第五个 then 块执行,打印 6。

【讨论】:

  • 承诺不执行;他们解决(或不解决)。
  • log 3 然后 4 的顺序并不总是正确的。它可能是 log 4 然后是 3。
  • @trincot 谢谢。我编辑了我的措辞。我一直在考虑措辞,但最终选择了错误的措辞。
  • @ikhvjs 我使用chrome开发者控制台尝试了那段代码,在3之前从来没有得到4。
猜你喜欢
  • 2023-03-09
  • 2016-08-07
  • 2020-03-13
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
相关资源
最近更新 更多