Promise A+ 标准
引用部分为原文, 括弧内为译者注
An open standard for sound, interoperable JavaScript promises—by implementers, for implementers.
一份开放的标准,为了能在不同JavaScript promises实现之间稳定地交互——从实现者中来,到实现者里去。
A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its
thenmethod, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled.This specification details the behavior of the
thenmethod, providing an interoperable base which all Promises/A+ conformant promise implementations can be depended on to provide. As such, the specification should be considered very stable. Although the Promises/A+ organization may occasionally revise this specification with minor backward-compatible changes to address newly-discovered corner cases, we will integrate large or backward-incompatible changes only after careful consideration, discussion, and testing.Historically, Promises/A+ clarifies the behavioral clauses of the earlier Promises/A proposal, extending it to cover de facto behaviors and omitting parts that are underspecified or problematic.
Finally, the core Promises/A+ specification does not deal with how to create, fulfill, or reject promises, choosing instead to focus on providing an interoperable
thenmethod. Future work in companion specifications may touch on these subjects.
promise表现为异步操作的最后结果。其主要的交互方式便是通过promise的then方法注册回调函数去接收promise的最终值或是promise为何无法“fulfilled”的原因。
这份规范详细描述了then方法的行为,并提供了一个交互的基础:所有基于Promises/A+规范实现的promise都可以依赖这个基础来提供。 (以确保它们在使用then方法时都表现一致) 尽管Promises/A+组织偶尔会修正这份规范,去兼容那些新发现的边缘情况(角落案例),但我们只会在经过仔细考虑、讨论和测试之后才会发布那些大的或者向后不兼容的改变。
从历史上来说,Promises/A+比起早期的Promises/A规范明确了行为条款,将其扩展并覆盖了实际行为,省略了一些未说明和存在问题的部分。
最后,Promises/A+规范的核心并非处理如何创建、完成或拒绝promises,而是聚焦于如何提供一个具有交互性的 then 方法。可能未来会在相关规范中涉及这些主题。
Terminology - 术语
- “promise” is an object or function with a
thenmethod whose behavior conforms to this specification.- “thenable” is an object or function that defines a
thenmethod.- “value” is any legal JavaScript value (including
undefined, a thenable, or a promise).- “exception” is a value that is thrown using the
throwstatement.- “reason” is a value that indicates why a promise was rejected.
- "promise":"promise"是指一个具有
then方法且其行为符合此规范的对象或函数。 - "thenable":"thenable"是指一个具有
then方法的对象或函数。 - "value":"value"指的是任何合法的JavaScript值(包括
undefined、一个"thenable"对象或一个Promise对象)。 - "exception":"exception"是指使用
throw语句抛出的值。 - "reason":"reason"是指指示为什么一个Promise被拒绝的值。
Requirements - 规定
Promise States - Promise 状态
A promise must be in one of three states: pending, fulfilled, or rejected.
When pending, a promise:
- may transition to either the fulfilled or rejected state.
When fulfilled, a promise:
- must not transition to any other state.
- must have a value, which must not change.
When rejected, a promise:
- must not transition to any other state.
- must have a reason, which must not change.
Here, “must not change” means immutable identity (i.e.
===), but does not imply deep immutability.
一个promise必须具有以下三种状态之一:等待(pending), 完成(fulfilled), 拒绝(rejected).
-
等待状态时
- 可以变换为完成或拒绝状态
-
完成状态时
- 不可以变换为其他状态
- 必须有一个不会改变的值
-
拒绝状态时
- 不可以变换为其他状态
- 必须有一个不会改变的原因
在这里的"不会改变"指的是不可变性(严格相等),不过并不意味着深层不可变性(嵌套)。
The then Method - then方法
A promise must provide a
thenmethod to access its current or eventual value or reason. Here, “must not change” means immutable identity (i.e.===), but does not imply deep immutability.
Both
onFulfilledandonRejectedare optional arguments:
- If
onFulfilledis not a function, it must be ignored.- If
onRejectedis not a function, it must be ignored.If
onFulfilledis a function:
- it must be called after
promiseis fulfilled, withpromise’s value as its first argument.- it must not be called before
promiseis fulfilled.- it must not be called more than once.
If
onRejectedis a function,
- it must be called after
promiseis rejected, withpromise’s reason as its first argument.- it must not be called before
promiseis rejected.- it must not be called more than once.
onFulfilledoronRejectedmust not be called until the execution context stack contains only platform code. [3.1].
onFulfilledandonRejectedmust be called as functions (i.e. with nothisvalue). [3.2]
thenmay be called multiple times on the same promise.
- If/when
promiseis fulfilled, all respectiveonFulfilledcallbacks must execute in the order of their originating calls tothen.If/when
promiseis rejected, all respectiveonRejectedcallbacks must execute in the order of their originating calls tothen.
thenmust return a promisepromise2 = promise1.then(onFulfilled, onRejected);
- If either
onFulfilledoronRejectedreturns a valuex, run the Promise Resolution Procedure[[Resolve]](promise2, x).- If either
onFulfilledoronRejectedthrows an exceptione,promise2must be rejected witheas the reason.- If
onFulfilledis not a function andpromise1is fulfilled,promise2must be fulfilled with the same value aspromise1.- If
onRejectedis not a function andpromise1is rejected,promise2must be rejected with the same reason aspromise1.
一个Promise对象必须提供一个then方法,用于访问它的当前值或最终的值(fulfillment)或拒绝的原因(rejection)。
一个promise的then方法需要接受两个参数:promise.then(onFulfilled, onRejected)
-
onFulfilled和onRejected都是可选参数- 如果
onFulfilled不是函数,必须被忽略 - 如果
onRejected不是函数,必须被忽略
- 如果
-
如果
onFulfilled是函数:- 它必须在
promise完成之后被调用,promise的value将成为它的第一个参数。 - 它不能在
promise完成之前被调用。 - 它不能被调用超过一次。
- 它必须在
-
如果
onRejected是函数:- 它必须在
promise拒绝之后被调用,promise的reason将成为它的第一个参数。 - 它不能在
promise拒绝之前被调用。 - 它不能被调用超过一次。
- 它必须在
-
onFulfilledoronRejected回调函数必须在执行上下文栈(execution context stack)中只包含平台代码(platform code)时才能被调用。
(在JavaScript中,执行上下文栈是一个用于管理函数调用和代码执行的机制。当一个函数被调用时,它的执行上下文会被推入栈中,当函数执行完成后,执行上下文会从栈中弹出。平台代码指的是JavaScript运行环境(如浏览器或Node.js)提供的内置函数、方法或事件处理程序等,而不是由开发者编写的自定义代码。这意味着在执行Promise的回调函数之前,所有正在进行的自定义代码执行已经完成,避免了回调函数执行过程中可能出现的意外行为或状态混乱。)
onFulfilled 与 onRejected 必须被作为函数调用 (即没有 this 值).
-
then可以在同一个promise上被多次调用.- 如果
promise完成,所有对应的onFulfilled回调函数必须按照它们调用then的顺序依次执行。 - 如果
promise拒绝,所有对应的onRejected回调函数必须按照它们调用then的顺序依次执行。
- 如果
-
then必须返回一个promisepromise2 = promise1.then(onFulfilled, onRejected);- 如果
onFulfilled或onRejected返回一个值x,则需要运行Promise Resolution Procedure(Promise解决过程) - 如果
onFulfilled或onRejected抛出一个异常e,promise2必须以e为reason拒绝。 - 如果
onFulfilled不是函数并且promise1完成,promise2必须也完成并与promise1使用同样的value. - 如果
onRejected不是函数并且promise1拒绝,promise2必须也决绝并与promise1使用同样的reason.
- 如果
The Promise Resolution Procedure - Promise解决过程
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as
[[Resolve]](promise, x). Ifxis a thenable, it attempts to makepromiseadopt the state ofx, under the assumption thatxbehaves at least somewhat like a promise. Otherwise, it fulfillspromisewith the valuex. This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliantthenmethod. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonablethenmethods. To run[[Resolve]](promise, x), perform the following steps:
- If
promiseandxrefer to the same object, rejectpromisewith aTypeErroras the reason.- If
xis a promise, adopt its state [3.4]:
- If
xis pending,promisemust remain pending untilxis fulfilled or rejected.- If/when
xis fulfilled, fulfillpromisewith the same value.- If/when
xis rejected, rejectpromisewith the same reason.- Otherwise, if
xis an object or function,- Let
thenbex.then. [3.5]- If retrieving the property
x.thenresults in a thrown exceptione, rejectpromisewitheas the reason.- If
thenis a function, call it withxasthis, first argumentresolvePromise, and second argumentrejectPromise, where:
- If/when
resolvePromiseis called with a valuey, run[[Resolve]](promise, y).- If/when
rejectPromiseis called with a reasonr, rejectpromisewithr.- If both
resolvePromiseandrejectPromiseare called, or multiple calls to the same argument are made, the first call takes precedence, and any further calls are ignored.- If calling
thenthrows an exceptione,
- If
resolvePromiseorrejectPromisehave been called, ignore it.- Otherwise, reject
promisewitheas the reason.- If
thenis not a function, fulfillpromisewithx.- If
xis not an object or function, fulfillpromisewithx. If a promise is resolved with a thenable that participates in a circular thenable chain, such that the recursive nature of[[Resolve]](promise, thenable)eventually causes[[Resolve]](promise, thenable)to be called again, following the above algorithm will lead to infinite recursion. Implementations are encouraged, but not required, to detect such recursion and rejectpromisewith an informativeTypeErroras the reason. [3.6]
Promise解决过程是一个抽象操作,它接受一个Promise和一个值作为输入,表示为[[Resolve]](promise, x)。如果x是一个"thenable"(具有then方法/可以被链式调用的),它试图让promise采用x的状态, 除非x的行为至少在某种程度上像是一个promise.否则,它将完成promise,并且让x成为这个promise的 value .
"thenables"处理方案允许不同promise实现 相互操作,只要他们都暴露遵循Promises/A+的then方法, 它也允许 Promises/A+ 实现“吸收”不符合规范但具有合理then方法的实现。
为了运行[[Resolve]](promise, x), 进行以下步骤:
-
如果
promise与x提交了同一个对象, 以TypeError为reason拒绝promise. -
如果
x是一个promise, 则采用x的状态.- 如果
x为等待态,promise必须等待到x完成或拒绝. - 如果/当
x完成, 以相同的value完成promise. - 如果/当
x拒绝, 以相同的reason拒绝promise
- 如果
-
另一种可能, 如果
x是对象或者函数,- 让
then变为x.then. - 如果检索
x.then属性(property) 结果抛出了一个异常e, 则用e作为reason拒绝promise - 如果
then是一个函数, 则调用它并以x作为this, 第一个参数为resolvePromise, 第二个参数为rejectPromise.- 如果/当
resolvePromise以y为value被调用, 则运行[[Resolve]](promise, y). - 如果/当
rejectPromise以r为reason被调用, 以r拒绝promise. - 如果/当
resolvePromise和rejectPromise都被调用, 或者对同一个参数进行了多次调用,那么第一次调用将优先生效,并且后续的调用将被忽略。 - 如果调用
then的过程中抛出异常e,- 如果
resolvePromise或者rejectPromise被调用, 则忽略它(这个异常). - 否则, 以
e为原因拒绝promise
- 如果
- 如果/当
- 如果
then不是函数, 以x完成promise.
- 让
-
如果
x不是函数或者对象, 以x完成promise.
如果一个promise 被解决为一个thenable,并且这个thenable参与了一个循环thenable链,导致[[Resolve]](promise, thenable)在递归过程中再次被调用,按照上述算法可能会导致无限递归。为了避免这种情况,Promises/A+规范鼓励但不强制要求实现检测到这样的递归,并用一个带有信息的TypeError作为原因来拒绝promise。
Notes - 注释
Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that
onFulfilledandonRejectedexecute asynchronously, after the event loop turn in whichthenis called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such assetTimeoutorsetImmediate, or with a “micro-task” mechanism such asMutationObserverorprocess.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.That is, in strict mode
thiswill beundefinedinside of them; in sloppy mode, it will be the global object.Implementations may allow
promise2 === promise1, provided the implementation meets all requirements. Each implementation should document whether it can producepromise2 === promise1and under what conditions.Generally, it will only be known that
xis a true promise if it comes from the current implementation. This clause allows the use of implementation-specific means to adopt the state of known-conformant promises.This procedure of first storing a reference to
x.then, then testing that reference, and then calling that reference, avoids multiple accesses to thex.thenproperty. Such precautions are important for ensuring consistency in the face of an accessor property, whose value could change between retrievals.Implementations should not set arbitrary limits on the depth of thenable chains, and assume that beyond that arbitrary limit the recursion will be infinite. Only true cycles should lead to a
TypeError; if an infinite chain of distinct thenables is encountered, recursing forever is the correct behavior.
- 这里的"平台代码"意思是引擎/环境/
promise实现代码。 事实上, 这个要求确保了onFulfilled和onRejected回调异步执行,也就是then方法事件循环的下一个循环周期中,并在一个新的执行栈上执行。 这可以通过“宏任务”机制,比如setTimeout或setImmediate,或者“微任务”机制,比如MutationObserver或process.nextTick来实现。由于Promise实现被视为平台代码,它本身可能包含一个任务调度队列或“跳板(trampoline)”,用于调用处理程序(handlers)。 (跳板是一种控制流的技术,用于在执行回调函数时避免出现深度递归调用。由于JavaScript是单线程的,深度递归调用可能导致栈溢出。使用跳板技术,可以将回调函数的执行放入任务队列中,从而保持执行上下文的切换,避免了深度递归调用导致的栈溢出问题。) - 在严格模式(strict mode)下,回调函数(onFulfilled和onRejected)中的this将为undefined;而在非严格模式(sloppy mode,也称为默认模式)下,this将指向全局对象。
- 实现可以允许
promise2 === promise1,前提是实现满足所有要求。每个实现都应该记录是否会产生promise2 === promise1,以及在什么条件下会产生这种情况。 - 实现可以使用实现特定的方式来判断x是否为真正的Promise,并允许在采用已知符合规范的Promise状态时使用实现特定的优化或处理。在使用这个条款时,需要确保实现之间的一致性和兼容性,以确保代码在不同实现中的表现一致。
- 首先存储对 x.then 的引用,然后测试该引用,最后调用该引用的过程,避免了多次访问 x.then 属性。这样的预防措施对于确保在访问器属性面前的一致性很重要,因为其值可能在多次访问之间发生更改。
- 实现不应对thenable链的深度设置任意限制,并假设在超过该任意限制后,递归将是无限的。只有真正的循环(cycle)才应该导致 TypeError 错误;如果遇到无限不同的thenables链,递归是正确的行为。