【问题标题】:Why then doesn't keep the order of the callbacks?那么为什么不保持回调的顺序呢?
【发布时间】:2021-04-14 16:23:12
【问题描述】:

我有以下代码:

Promise
  .resolve('333')
  .then(()=>{setTimeout(()=>{Promise.resolve('123');},10000)})
  .then(()=>{console.log("should wait");});

我认为输出应该首先是“123”,然后是“应该等待”。由于不明原因,首先打印了“应该等待”。我认为直到异步函数(setTimeout)没有完成,第二个才会开始。我读到这就是使用Promisethen 的全部“魔法”。现在我很困惑。为什么例如当我们调用 fetch 函数时它不会发生? fetch 函数也是异步的,那么为什么 fetch 结束之前 fetch 之后的 then 没有开始呢?

【问题讨论】:

  • 你的承诺链不会等待超时。

标签: javascript asynchronous promise fetch


【解决方案1】:

除非 .then 回调显式返回 Promise,否则链中的下一个 .then 保证在之后几乎立即运行(它被放入微任务队列)。

现在,你没有返回任何东西,所以 undefined 被返回,所以第二个 .then 立即运行。

如果您希望第一个 .then 导致第二个等待超时完成,请返回一个在超时解决时解决的 Promise:

Promise.resolve('333')
    .then(() => {
        return new Promise((res) => {
          setTimeout(() => {
            res('123');
          }, 3000);
        });
     })
    .then(() => { console.log("should wait 3 seconds"); });

【讨论】:

  • Promise 是否必须包裹setTimeout?不能是另一种方式:setTimeout 将包装 Promise?
  • 否,因为回调返回的值必须是Promise。 .then 回调不知道如何处理超时 ID。 Promise 必须包装 setTimeout
  • 是否可以说,在我的情况下,promise 被解决为立即履行,因此 next then 可以立即开始?
  • 在您的原始代码中,链中唯一的 Promise 是执行 Promise.resolve('333') 的原始 Promise。 .then里面的Promise不是从.then返回的,所以下一个.then不等待。
猜你喜欢
  • 2018-08-01
  • 2016-01-21
  • 2015-11-16
  • 2013-02-02
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 2011-01-17
  • 2022-11-26
相关资源
最近更新 更多