关于前端:promise实现原理面试

//创立一个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);
      }
    }
  }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理