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

6次阅读

共计 680 个字符,预计需要花费 2 分钟才能阅读完成。

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