javascript - 当 promise 被多次解决时会发生什么

标签 javascript es6-promise

如果多次拒绝/解决 ES6 promise ,标准行为是什么?

以下代码仅在 Google Chrome 中被解析一次,这是所有浏览器的标准行为吗?

new Promise(function(e) {
    $('#button').click(function(){
        resolve();
    });
});

我看到一个promise polyfill在尝试解决已经解决的 promise 时抛出异常。 es6-promise 的规范是否指定了这一点,或者不符合 polyfill 标准?

更新

抱歉,我刚刚意识到它不是 polyfill,而只是 Promise(非标准)的最小实现。

最佳答案

一个 promise 不能被多次解决或解决。一旦 promise 被解决、履行或拒绝,进一步的解决或解决它的调用将被忽略。 (如果这些术语不熟悉或只是模糊地熟悉,我已经写过关于 promise 术语的文章 on my blog。) 不会引发错误。

I have seen a promise polyfill throwing an exception on trying to resolve an already resolved promise. Does the specification for es6-promise specify this...?

没有。这包含在 Promise Resolve Functions 中, 这说明了他们的工作。以下是前几个步骤:

When a promise resolve function is called with argument resolution, the following steps are taken:

  1. Let F be the active function object.
  2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  3. Let promise be F.[[Promise]].
  4. Let alreadyResolved be F.[[AlreadyResolved]].
  5. If alreadyResolved.[[Value]] is true, return undefined.

(我的重点)

有些人认为尝试解决或解决已经解决或解决的 promise 应该是错误的。由于它没有进入 ES2015 规范,它可能永远不会被添加,因为它不会向后兼容现有代码。

关于javascript - 当 promise 被多次解决时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43361492/

相关文章:

javascript - Angular js 服务值不会在 View 中更新

javascript - "Can only send requests to friends or users of this application"

javascript - 直接返回 Promise 中的对象

javascript - 监听 Promise 何时在执行器函数内解析

javascript - NodeJS Promise 和 Symbol.species 的使用

javascript - 如何区分移动版 Google Maps JS API v3 中的点击和拖动?

javascript - 使用 XMLHttpRequest 抑制控制台错误

javascript - 从 Promise 返回数据并在另一个方法中获取它

javascript - Promise reject - 超时日志记录放置

javascript - 避免使用 jquery 多次选择相同的选项