【问题标题】:Promise `then` with a function returning nothing vs with a function returning an another promisePromise `then` 函数不返回任何内容与函数返回另一个 Promise
【发布时间】:2020-01-16 09:34:23
【问题描述】:

我不明白为什么我们执行这段代码会产生如此奇怪的结果。

为什么没有 12121212 的图像?在每个 1 之后,我们有三个 2。

Promise.resolve()
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); });

Promise.resolve()
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); });

【问题讨论】:

  • 可能与 new Promise 必须首先解包有关
  • 两个promise链异步运行,无法预测它们各自解析的顺序。
  • 它们都是微任务。并将在微任务阶段解决。只需查看微任务即可了解所有内容。

标签: javascript promise


【解决方案1】:

这是因为在用另一个 Promise 解决该 Promise 时涉及多个滴答声。

但实际上,您应该忽略这一点,并且永远不要依赖独立的 Promise 链之间的时间安排。

【讨论】:

  • 是的:但实际上,你应该忽略这一点,并且永远不要依赖独立的承诺链之间的时间安排。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 2021-03-17
  • 2020-06-20
  • 2017-09-13
  • 2023-03-21
  • 1970-01-01
  • 2018-05-08
相关资源
最近更新 更多