2020.04.01
then 方法的对象或函数,其行为遵守本规范。then 方法的对象或函数。undefined、一个 thenable 或者一个 promise)。throw 申明抛出的值。一个 Promise 必须是三种状态之一: pending,fulfilled 或者 rejected。
value,且必须不变。reason,且必须不变。这里的”必须不变”指的是定义不变(i.e. ===),但并不表示深度不变。
then 方法一个 promise 必须要提供一个 then 方法来访问其当前或最终的 value 或者 reason。
一个 promise 的 then 方法接受两个参数:
promise.then(onFulfilled, onRejected)
onFulfilled 和 onRejected 都是可选参数:
onFulfilled 不是一个函数,那么它会被忽略。onRejected 不是一个函数,那么它会被忽略。onFulfilled 是一个函数:
promise 的 value 作为第一个入参。onRejected 是一个函数:
promise 的 reason 作为第一个入参。onFulfilled 或者 onRejected 不能被调用;onFulfilled 和 onRejected 必须被作为函数来被调用;then 方法可以被多次调用:
onFulfilled 回调函数必须按照对原始 then 方法调用的顺序顺序执行。onRejected 回调函数必须按照对原始 then 方法调用的顺序顺序执行。then 方法必须返回一个 promise:
onFulfilled 或者 onRejected 返回了一个 value x,执行 promise resolution procedure [[Resolve]](promise2, x)。onFulfilled 或者 onRejected 抛出了一个 exception e,promise2 必须以 e 为 reason 被 rejected。onFulfilled 不是一个函数且 promise1 是 fulfilled 状态,promise2 必须是 fufilled 状态且有和 promise1 相同的 value。onRejected 不死一个函数且 promise1 是 rejected 状态,promise2 必须是 rejected 状态且有和 promise1 相同的 reason。promise2 = promise1.then(onFulfilled, onRejected)
promise resolution procedure是一个抽象的操作,它接收一个 promise 和一个 value 作为入参,我们将之记作 [[Resolve]](promise, x),如果 x 是一个 thenable,在 x 的行为至少类似于 promise 的前提下,将 x 的状态运用于 promise。否则,使用 x 作为 fulfill promise 的 value。
运行 [[Resolve]](promise, x) 将表现为如下步骤:
promise 和 x 指向同一个对象,那么 promise 会以 TypeError 作为 reason 来 reject。x 是一个 promise,则使用它的状态:
x 是等待状态,那么 promise 必须维持等待状态,直到 x 的状态变更为 fulfilled 或者 rejectedx 是 fulfilled 状态,那么 promise 也以同样的 value 转变为 fulfilled 状态x 是 rejected 状态,那么 promise 也以同样的 reason 转变为 rejected 状态x 是一个对象或者一个函数:
x.then 定义一个 thenx.then 属性导致抛出一个异常 e,那么以 e 为 reason 将 promise 转变为 rejcted 状态then 是一个函数, 调用 call 方法,同时将 x 作为this,第一个参数是 resolvePromise,第二个参数是 rejectPromise:
resolvePromise 被执行,并且 value 的值为 y,执行 [[Resolve]](promise, y)rejectPromise 被执行,并且 reason 的值为 r,以 r 为 reason 将 promise 变更为 rejected 状态resolvePromise 或 rejectPromise 只能被调用一个,且只能被调用一次,如果调用多次,第一次有效。then 抛出异常 e:
resolvePromise 或者 rejectPromise 被调用过了,那么忽略异常e 作为 reason 将 promise 的状态变更为 rejected;then 不是一个函数,以 x 为 value 将 promise 状态变更为 fulfilled;x 不是一个对象或者函数,以 x 为 value 将 promise 状态变更为 fulfilled;