美文网首页
实现简单的Promise

实现简单的Promise

作者: TRYao | 来源:发表于2018-06-01 14:58 被阅读0次
    class Promise{
      constructor(executor){
        // 默认是等待状态
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        // 存放成功回调函数
        this.onResolveCallbacks = [];
        this.onRejectedCallbacks = [];
        let resolve = (data) => {
          // this指的是实例
          if(this.status === 'pending'){
            this.value = data;
            this.status = 'resolved';
            this.onResolveCallbacks.forEach(fn=>fn());
          }
        }
        let reject = (reason) => {
          // this指的是实例
          if(this.status === 'pending'){
            this.value = reason;
            this.status = 'rejected';
            this.onRejectedCallbacks.forEach(fn=>fn());
          }
        }
        // 执行时可能发生异常
        try{ 
          executor(resolve,reject);
        }catch(e){
          reject(e);
        }
      }
      then(onFulfilled,onRejected){
        if(this.status === 'resolve'){
          onFulfilled(this.value);
        }
        if(this.status === 'reject'){
          onRejected(this.value);
        }
        if(this.status === 'pending'){
          this.onReslovedCallbacks.push(()=>{
            onFulfilled(this.value);
          })
          this.onRejectedCallbacks.push(()=>{
            onRejected(this.reason);
          })
        }
      }
    }
    

    参考文章:Promise不会??看这里!!!史上最通俗易懂的Promise!!!

    相关文章

      网友评论

          本文标题:实现简单的Promise

          本文链接:https://www.haomeiwen.com/subject/ppcksftx.html