//创立一个Promise的类 class Promise{
constructor(executer){//构造函数constructor外面是个执行器 this.status = 'pending';//默认的状态 pending this.value = undefined//胜利的值默认undefined this.reason = undefined//失败的值默认undefined //状态只有在pending时候能力扭转 let resolveFn = value =>{
//判断只有期待时能力resolve胜利 if(this.status == pending){
this.status = 'resolve';
this.value = value;
}
}
//判断只有期待时能力reject失败 let rejectFn = reason =>{
if(this.status == pending){
this.status = 'reject';
this.reason = reason;
}
}
try{
//把resolve和reject两个函数传给执行器executer executer(resolve,reject);
}catch(e){
reject(e);//失败的话进catch }
}
then(onFufilled,onReject){
//如果状态胜利调用onFufilled if(this.status = 'resolve'){
onFufilled(this.value);
}
//如果状态失败调用onReject if(this.status = 'reject'){
onReject(this.reason);
}
}
}
发表回复