承诺多次解决后会发生什么 [英] What happens when a promise is resolved multiple times

查看:96
本文介绍了承诺多次解决后会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the standard behaviour if a ES6 promise is rejected / resolved multiple times?

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

The following code was only resolved once in Google Chrome, is this the standard behaviour in all browsers?

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

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

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, or isn't the polyfill standard compliant?

更新

对不起,我刚才意识到它不是一个polyfill,而只是一个Promise(非标准)的最小实现。

Sorry, I just realized that it is not a polyfill, but just a minimal implementation of a Promise (non standard).

推荐答案

承诺无法解决多次。一旦承诺得到解决(解决或拒绝),将再次调用解决(解决或拒绝)协议。没有错误。

A promise cannot be resolved more than once. Once the promise is settled (resolved or rejected), calls to settle (resolve or reject) it again are ignored. No error is raised.


我看到一个承诺polyfill在尝试解决已经解决的承诺时抛出异常。 es6-promise的规范是否指定了这个......?

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 ,说明他们做了什么。以下是前四个步骤:

No, it does not. This is covered in Promise Resolve Functions, which says what they do. Here are the first four steps:


当使用参数解析调用promise resolve函数F时,将执行以下步骤:

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


  1. 断言:F有一个[[Promise]]内部插槽,其值为Object。

  2. 让我们保证是F的[[Promise]]内部插槽的值。

  3. 让已经解决的是F的[[AlreadyResolved]]内部插槽的值。

  4. 如果已经已解决。[[值]]为真,则返回未定义。

  5. ...

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


(我的重点)

有人认为试图解决既定的承诺应该是一个错误。由于这不符合ES2015的规范,因此可能很难添加它,即使他们能够找到TC-39冠军来提出这样做​​。它可能最终必须是一个标志或 Promise 子类,并且可以随时添加一个自己的 Promise 子类,如果这是人们想要的行为。

There are people who argue that attempting to settle a settled promise should be an error. Since that didn't make it into the spec for ES2015, it will probably be hard to add it, even if they could find a TC-39 champion for a proposal to do so. It would probably end up having to be a flag or Promise subclass, and one can readily add one's own Promise subclass if this is the behavior one wants.

这篇关于承诺多次解决后会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆