手寫基於Promise A+規範的Promise

const PENDING =  'pending';//初始態const FULFILLED =  'fulfilled';//初始態const REJECTED =  'rejected';//初始態function Promise(executor){  let self = this;//先緩存當前promise實例  self.status = PENDING;//設置狀態  //定義存放成功的回調的數組  self.onResolvedCallbacks = [];  //定義存放失敗回調的數組  self.onRejectedCallbacks = [];  //當調用此方法的時候,若是promise狀態爲pending,的話能夠轉成成功態,若是已是成功態或者失敗態了,則什麼都不作  //2.1  function resolve(value){ //2.1.1    if(value!=null &&value.then&&typeof value.then == 'function'){      return value.then(resolve,reject);    }    //若是是初始態,則轉成成功態    setTimeout(function(){      if(self.status == PENDING){        self.status = FULFILLED;        self.value = value;//成功後會獲得一個值,這個值不能改        //調用全部成功的回調        self.onResolvedCallbacks.forEach(cb=>cb(self.value));      }    })  }  function reject(reason){ //2.1.2    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);  };}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);  }}//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);         }     });   });  }}//catch原理就是隻傳失敗的回調Promise.prototype.catch = function(onRejected){    this.then(null,onRejected);}Promise.deferred = Promise.defer = function(){  let defer = {};  defer.promise = new Promise(function(resolve,reject){    defer.resolve = resolve;    defer.reject = reject;  });  return defer;}function gen(times,cb){  let result = [],count=0;  return function(i,data){    result[i] = data;    if(++count==times){      cb(result);    }  }}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);   } });}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對象Promise.resolve = function(value){  return new Promise(function(resolve){    resolve(value);  });}//返回一個馬上失敗的promisePromise.reject = function(reason){  return new Promise(function(resolve,reject){    reject(reason);  });}module.exports = Promise;
相關文章
相關標籤/搜索