【问题标题】:Why isn't the callback within Promise deferred to be run? [duplicate]为什么 Promise 中的回调不延迟运行? [复制]
【发布时间】:2016-07-27 05:03:11
【问题描述】:

以下是一个演示:

var forever = new Promise(function (resolve, reject) {
  while (true) {
  }
  resolve("done")

});
console.log("Promise returned")

console.log("Promise returned") 永远不会被执行。似乎forever 的评估将阻塞线程并且永远不会返回。

将函数体包装成setTimeout 修复了这个问题:

var forever = new Promise(function (resolve, reject) {
  setTimeout(function() {
    while (true) {
    }
    resolve("done")
  },0)

});
console.log("Promise returned")

Promise的回调参数不应该deferred被执行吗(不需要被setTimeout包裹)?有没有关于这种行为的文档?

【问题讨论】:

  • 没有。如果你在 Promise 中包装一个进行 ajax 调用的函数,它会推迟通过网络进行调用吗?
  • 不,没有理由推迟执行人。是的,这是记录在案的;我会寻找骗子。教训是你不应该在你的代码中放置无限循环。
  • 这段代码有什么意义?创建一个永远不会解决的承诺可以很多更容易。

标签: javascript asynchronous promise ecmascript-6


【解决方案1】:

传递给new Promise()的函数被同步调用。它可能会调用其他异步函数,并在这些函数的回调中解析(或拒绝)promise,但如果您直接在该顶级函数中执行while (true),它立即阻止浏览器。

【讨论】:

  • while(true){} 将始终阻止浏览器,无论您何时执行它:-)
  • @Bergi 公平点 - 现在合格:)
【解决方案2】:

Section 25.4.3.1 的规范声明“当使用参数执行器调用 Promise 函数时”会采取以下步骤:

  1. 让完成为Call(executor, undefined, «resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]]»)

因此,规范要求在构造过程中调用Promise 构造函数的回调。 MDN notes this 也是:

executor函数立即执行。

executor 函数不一定需要立即调用resolvereject,而是在new Promise 返回之前调用自身。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2021-08-29
    • 2016-08-09
    • 2016-12-21
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多