一、基本思路
promise是一个构造函数,接受一个executor作为参数,executor会立即执行且接受两个参数函数,两个函数用来改变promise状态(只可改变一次)。promise实例有一个then方法,then方法接受两个参数函数,第一个参数函数接受一个value,在promise状态改变为fulfilled后执行;第二个参数函数接受一个reason,在promise状态变为rejected后调用。
小细节:如果executor执行抛出了异常,promise状态会变成rejected,执行executor时要用try,catch捕获异常,必要时改变promise状态
二、基本实现
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
class MyPromise{
constructor(executor){
this.status = PENDING;
this.value = undefined; // value promise为fulfilled状态时的值
this.reason = undefined; // reason promise边为rejected状态时的原因
const resolve = (val)=>{
// 细节 promise状态只能从pending变为fulfilled或者rejected,所以判断之前要判断
if(this.status === PENDING){
this.status = FULFILLED;
this.value = val
}
};
const reject = (val)=>{
if(this.status === PENDING){
this.status = REJECTED;
this.reason = val
}
}
try{
executor(resolve,reject)
}catch(e){
reject(e)
}
}
then(onFulfilled,onRejected){
if(this.status === FULFILLED){
onFulfilled(this.value)
}else if (this.status === REJECTED){
onRejected(this.reason)
}
}
}