const FULLFILLED='FULLRILLED' const REJECTED='REJECTED' class p{ constructor(excutor){ try{ excutor(this.resolve,this.reject) }catch(err){ console.log(err) } } status=PENGDING successVal=undefined failReson=undefined successCbs=[] failCbs=[] resovle=v=>{ if(this.status! ==PENGDING) return this.status=FULLFILLED this.successVal=v while(successCbs.length) successCbs.shift()(v) } reject=v=>{ if(this.status! ==PENGDING) return this.status=REJECTED this.failReson=v while(failCbs.length) failCbs.shift()(v) } then=(successCb,failCb)=>{ const backPromise=new P((resolve,reject)=>{ if(this.status===FULLFILLED){ let res=successCb(this.successVal) resolvePromise(res,resolve,reject) }else if(this.status===REJECTED){ let Res =failCb(this.failreson) resolvePromise(res,resolve,reject)}else{// Asynchronous task this.successcbs.push (()=>{let res=successCb(this.successVal) resolvePromise(res,resolve,reject) }) this.failCbs.push(()=>{ let res=failCb(this.successVal) resolvePromise(res,resolve,reject) }) } }) return backPromise } static all=(promises)=>{ let len=promises.length let index=0 let res=[] return new P((resolve,reject)=>{ function add(key,val){ res[key]=val index++ if(index===len){ resolve(res) } } for(let i=0; i<len; i++){ let target=promises[i] if(target instanceof P){ target.then(v=>{ add(i,v) },v=>reject(v)) }else{ add(i,promises[i]) } } }) } static race=(promises)=>{ return new P((resolve,reject)=>{ for(let i=0; i<promises.length; i++){ P.resolve(promises[i]).then(data=>{ resolve(data) return }).catch(err=>{ reject(err) return }) } }) } static resolve=(param)=>{ if(param instanceof P){ return param }else{ return new P((resolve,reject)=>{ resolve(param) }) } } static reject=param=>{ return new P((resolve,reject)=>{ reject(param) }) } static finally=callback=>{ this.then(val=>{ return P.resolve(callback()).then(()=>val) },err=>{ return P.resolve(callback()).then(()=>{throw err}) }) } } function resolvePromise(res,resolve,reject){ if(res instanceof P){ res.then(resolve,reject) }else{ resolve(res) } } //1. Basic framework //2. Consider if Excutor performs asynchronous tasks //3. Consider the chained calls to THEN and the upper-level THEN returns promise //4. Error handling //5. Implementation of all //6. Implementation of raceCopy the code