手動實現一個promise(原始碼)

小圖子發表於2019-02-27

1. 定義三個狀態

const PENDING =  'pending';//初始態
const FULFILLED =  'fulfilled';//初始態
const REJECTED =  'rejected';//初始態
複製程式碼

1. 定義建構函式主題部分

function Promise(executor){
  let self = this; //先快取當前promise例項
  self.status = PENDING;//設定狀態
  //定義存放成功的回撥的陣列
  self.onResolvedCallbacks = [];
  //定義存放失敗回撥的陣列
  self.onRejectedCallbacks = [];
  //當呼叫此方法的時候,如果promise狀態為pending,的話可以轉成成功態,如果已經是成功態或者失敗態了,則什麼都不做
 
  //2.1 定義resolve方法;
  function resolve(value){  
    if(value!=null &&value.then&&typeof value.then == 'function'){
      return value.then(resolve,reject);
    }
    //如果是初始態,則轉成成功態
    //為什麼要把它用setTimeout包起來
    setTimeout(function(){
      if(self.status == PENDING){
        self.status = FULFILLED;
        self.value = value;//成功後會得到一個值,這個值不能改
        //呼叫所有成功的回撥
        self.onResolvedCallbacks.forEach(cb=>cb(self.value));
      }
    })
  }
   //2.1.2 定義reject方法;
  function reject(reason){ 
    setTimeout(function(){
      //如果是初始態,則轉成失敗態
      if(self.status == PENDING){
        self.status = REJECTED;
        self.value = reason;//失敗的原因給了value
        self.onRejectedCallbacks.forEach(cb=>cb(self.value));
      }
    });
  }
  try{
    //因為此函式執行可能會異常,所以需要捕獲,如果出錯了,需要用錯誤 物件reject
    executor(resolve,reject);
  }catch(e){
    //如果這函式執行失敗了,則用失敗的原因reject這個promise
    reject(e);
  };
}

複製程式碼

2. 例項擴充套件方法

2.1 then()方法;

//onFulfilled 是用來接收promise成功的值或者失敗的原因
Promise.prototype.then = function(onFulfilled,onRejected){
  //如果成功和失敗的回撥沒有傳,則表示這個then沒有任何邏輯,只會把值往後拋
  //2.2.1
  onFulfilled = typeof onFulfilled == 'function'?onFulfilled:function(value){return  value};
  onRejected = typeof onRejected == 'function'?onRejected:reason=>{throw reason};
  //如果當前promise狀態已經是成功態了,onFulfilled直接取值
  let self = this;
  let promise2;
  if(self.status == FULFILLED){
    return promise2 = new Promise(function(resolve,reject){
      setTimeout(function(){
        try{
          let x =onFulfilled(self.value);
          //如果獲取到了返回值x,會走解析promise的過程
          resolvePromise(promise2,x,resolve,reject);
        }catch(e){
          //如果執行成功的回撥過程中出錯了,用錯誤原因把promise2 reject
          reject(e);
        }
      })

    });
  }
  if(self.status == REJECTED){
    return promise2 = new Promise(function(resolve,reject){
      setTimeout(function(){
        try{
          let x =onRejected(self.value);
          resolvePromise(promise2,x,resolve,reject);
        }catch(e){
          reject(e);
        }
      })
    });
  }
  if(self.status == PENDING){
   return promise2 = new Promise(function(resolve,reject){
     self.onResolvedCallbacks.push(function(){
         try{
           let x =onFulfilled(self.value);
           //如果獲取到了返回值x,會走解析promise的過程
           resolvePromise(promise2,x,resolve,reject);
         }catch(e){
           reject(e);
         }

     });
     self.onRejectedCallbacks.push(function(){
         try{
           let x =onRejected(self.value);
           resolvePromise(promise2,x,resolve,reject);
         }catch(e){
           reject(e);
         }
     });
   });
  }

}
複製程式碼

2.2 resolvePromise方法;

function resolvePromise(promise2,x,resolve,reject){
  if(promise2 === x){
    return reject(new TypeError('迴圈引用'));
  }
  let called = false;//promise2是否已經resolve 或reject了
  if(x instanceof Promise){
    if(x.status == PENDING){
      x.then(function(y){
        resolvePromise(promise2,y,resolve,reject);
      },reject);
    }else{
      x.then(resolve,reject);
    }
  //x是一個thenable物件或函式,只要有then方法的物件,
  }else if(x!= null &&((typeof x=='object')||(typeof x == 'function'))){
    //當我們的promise和別的promise進行互動,編寫這段程式碼的時候儘量的考慮相容性,允許別人瞎寫
   try{
     let then = x.then;
     if(typeof then == 'function'){
       //有些promise會同時執行成功和失敗的回撥
       then.call(x,function(y){
         //如果promise2已經成功或失敗了,則不會再處理了
          if(called)return;
          called = true;
          resolvePromise(promise2,y,resolve,reject)
       },function(err){
         if(called)return;
         called = true;
         reject(err);
       });
     }else{
       //到此的話x不是一個thenable物件,那直接把它當成值resolve promise2就可以了
       resolve(x);
     }
   }catch(e){
     if(called)return;
     called = true;
     reject(e);
   }

  }else{
    //如果X是一個普通 的值,則用x的值去resolve promise2
    resolve(x);
  }
}
複製程式碼

2.3 catch()方法;

//catch原理就是隻傳失敗的回撥
Promise.prototype.catch = function(onRejected){
  this.then(null,onRejected);
}
複製程式碼

2.4 deferred()方法;

Promise.deferred = Promise.defer = function(){
  let defer = {};
  defer.promise = new Promise(function(resolve,reject){
    defer.resolve = resolve;
    defer.reject = reject;
  });
  return defer;
}
複製程式碼

2.5 all()方法;

Promise.all = function(promises){
 return new Promise(function(resolve,reject){
   let done = gen(promises.length,resolve);
   for(let i=0;i<promises.length;i++){
     promises[i].then(function(data){
       done(i,data);
     },reject);
   }
 });
}

function gen(times,cb){
  let result = [],count=0;
  return function(i,data){
    result[i] = data;
    if(++count==times){
      cb(result);
    }
  }
}
複製程式碼

2.6 racel()方法;

Promise.race = function(promises){
  return new Promise(function(resolve,reject){
    for(let i=0;i<promises.length;i++){
      promises[i].then(resolve,reject);
    }
  });
}

//返回一個立刻成功的promise
//別人提供 給你一個方法,需要你傳入一個promise,但你只有一個普通的值,你就可以通過這個方法把這個普通的值(string number object)轉成一個promise物件
複製程式碼

2.7 resolve()方法;

Promise.resolve = function(value){
  return new Promise(function(resolve){
    resolve(value);
  });
}
複製程式碼

2.8 reject()方法;

//返回一個立刻失敗的promise
Promise.reject = function(reason){
  return new Promise(function(resolve,reject){
    reject(reason);
  });
}
複製程式碼

相關文章