class MyPromise{
constructor(executor){
this.initValue()
this.initBind()
try {
executor(this.resolve,this.reject)
}catch(e){
this.reject(e)
}
}
initValue(){
this.PromiseState='pending';
this.PromiseResult=null;
//因为一个promise实例可能会多次then,用数组就一个一个保存了
this.onFulfilledCallbacks=[] //保存成功回调
this.onRejectedCallbacks=[] //保存失败回调
}
initBind(){
this.resolve=this.resolve.bind(this);
this.reject=this.reject.bind(this);
}
resolve(value){
if(this.PromiseState!=='pending') return ;
this.PromiseState='fulfilled';
this.PromiseResult=value;
//执行保存的成功回调
while(this.onFulfilledCallbacks.length){
this.onFulfilledCallbacks.shift()(this.PromiseResult)
}
}
reject(reason){
if(this.PromiseState!=='pending') return;
this.PromiseState='rejected';
this.PromiseResult=reason;
//执行保存的失败回调
while(this.onRejectedCallbacks.length){
this.onRejectedCallbacks.shift()(this.PromiseResult)
}
}
then(onFulfilled,onRejected){//then函数会在调用promise的时候就执行,不会延时。因此这种情况需要先保存
//参数校验,确保一定是函数。不是函数时,会读到异常,此时执行reject
onFulfilled=typeof onFulfilled==='function'? onFulfilled:value=>value
//不是函数时,返回失败原因
onRejected=typeof onRejected==='function'?onRejected:reason=>{throw reason}
if(this.PromiseState==='fulfilled'){//如果当前为成功状态
//成功了就把成功的结果传给成功回调函数onFulfilled
onFulfilled(this.PromiseResult) //执行第一个回调
}else if(this.PromiseState==='rejected'){//如果当前为失败状态
onRejected(this.PromiseResult)//执行第二个回调
}else if(this.PromiseState==='pending'){//如果当前还未执行resolve或reject,则需要保存
this.onFulfilledCallbacks.push(onFulfilled.bind(this))
this.onRejectedCallbacks.push(onRejected.bind(this))
}
}
}
let test1=new MyPromise((resolve,reject)=>{
setTimeout(() => {
resolve('成功') // 1秒后输出 成功
// resolve('成功') // 1秒后输出 失败
}, 1000)
}).then(res=>console.log(res),err=>console.log(err))
console