如果多次拒绝/解决 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:
- Let F be the active function object.
- Assert: F has a [[Promise]] internal slot whose value is an Object.
- Let promise be F.[[Promise]].
- Let alreadyResolved be F.[[AlreadyResolved]].
- If alreadyResolved.[[Value]] is true, return undefined.
(我的重点)
有些人认为尝试解决或解决已经解决或解决的 promise 应该是错误的。由于它没有进入 ES2015 规范,它可能永远不会被添加,因为它不会向后兼容现有代码。
关于javascript - 当 promise 被多次解决时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43361492/