The core Promises/A+ specification does not deal with how to create, fulfill, or reject promises, choosing instead to focus on providing an interoperable
then
method. Future work in companion specifications may touch on these subjects.
这里按照ES6 Promise的接口实现
创建Promise时传入一个函数
(resolve, reject) => {}
,称为executor function
if(this.status ==='pending'){returnnewPromise((resolve, reject)=>{// this指向当前pending的这个promise// 即返回promise要执行的内容会保存在前一个promise里this.onFulfilledCallbacks.push((value)=>{try{const x =onFulfilled(value);resolve(x);}catch(e){reject(e);}});this.onRejectedCallbacks.push((reason)=>{try{const x =onRejected(reason);resolve(x);}catch(e){reject(e);}});});
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.
当x是thenable时,返回的promise会尽量继承x的状态;否则resolve(x)
(规范写得很详细,按照它实现就行,就不翻译了)
thenable
“thenable” is an object or function that defines a then method.
const p =newPromise((resolve)=>{resolve();
console.log(p2);// error but nothing happens});
x is thenable (2.3.3)
thenable判断
x is function or object (2.3.3)
x.then is function
保存x.then,之后通过保存的then调用 (2.3.3.1)
防止不同实现中,多次调用x.then返回不同的结果
如果获取x.then时抛出异常,则reject (2.3.3.2)
当x不是thenable,则resolve(x) (2.2.3.4,2.3.4)
执行then
以x为this调用then,传入resolvePromise和rejectPromise两个参数
resolvePromise(y)函数执行[[Resolve]](promise, y)
rejectPromise(r)函数reject promise with reason r
if(x !==null&&(typeof x ==='object'||typeof x ==='function')){try{
then = x.then;// 2.3.3.1 value could change between retrievalsif(typeof then ==='function'){// 2.3.3.3then.call((y)=>promiseResolutionProcedure(promise, y, resolve, reject),(r)=>reject(r)}else{resolve(x);// 2.3.3.4}catch(e){reject(e);// 2.3.3.2}else{resolve(x);// 2.3.4
// onFulfilled返回一个MyPromise// 它的executor以一个thenable作为参数调用resolveconst promise =newMyPromise((resolve)=>resolve('dummy')).then(()=>{returnnewMyPromise((resolve)=>{resolve(Promise.resolve(1));});});
promise.then(console.log, console.error);// should be 1
promise的值应当为1,而不是Promise.resolve(1)。参考x is thenable中的规则,应当继续通过Promise Resolution Procedure处理(thenable类型)的参数。
最终实现为:
if(x instanceofMyPromise){
x.then(// 递归调用promiseResolutionProcedure作为onFulfilled参数(y)=>promiseResolutionProcedure(promise, y, resolve, reject),
reject // reject不需要return;
与x is thenable情况相比,只是简化了判断thenable、避免多次调用、处理异常这些零碎部分。