es6中Promise對象

es6中Promise對象,代表一個異步操作,其不受外界影響,有三種狀態

* Pending(進行中、未完成的)

Resolved(已完成,又稱 Fulfilled)

Rejected(已失敗)

 

優勢1、解決回調地獄(Callback Hell)問題2、更好地進行錯誤捕獲

*

* Promise.then(成功回調).catch(錯誤或失敗回調)

* Promise.all([func1(),func2()]).then((返回值)=>{console.log()返回值是個數組["函數1返回值","函數2返回值"]})所有異步操作執行完後才執行回調。

 

那麼在es5用如何實現promise呢?

請看下方

//1、使用function創建一個MyPromise方法即構造函數 帶一個參數即回調函數fn

function MyPromise(fn) {
  this.value;
  this.status = 'pending';
  this.resolveFunc = function() {};
  this.rejectFunc = function() {};
  fn(this.resolve.bind(this), this.reject.bind(this));
}

//2 、給MyPromise添加一個原型方法resolve,將val值傳進去,利用

MyPromise.prototype.resolve = function(val) {
  var self = this;
  if (this.status == 'pending') {
    this.status = 'resolved';
    this.value = val;
    setTimeout(function() {
      self.resolveFunc(self.value);
    }, 0);
  }
}

//3 、給MyPromise添加一個原型方法reject,將val值傳進去,利用

MyPromise.prototype.reject = function(val) {
  var self = this;
  if (this.status == 'pending') {
    this.status = 'rejected';
    this.value = val;
    setTimeout(function() {
      self.rejectFunc(self.value);
    }, 0);
  }
}

MyPromise.prototype.then = function(resolveFunc, rejectFunc) {
  var self = this;
  return new MyPromise(function(resolve_next, reject_next) {
    function resolveFuncWrap() {
      var result = resolveFunc(self.value);
      if (result && typeof result.then === 'function') {
        //如果result是MyPromise對象,則通過then將resolve_next和reject_next傳給它
        result.then(resolve_next, reject_next);
      } else {
        //如果result是其他對象,則作爲參數傳給resolve_next
        resolve_next(result);
      }
    }
    function rejectFuncWrap() {
      var result = rejectFunc(self.value);
      if (result && typeof result.then === 'function') {
        //如果result是MyPromise對象,則通過then將resolve_next和reject_next傳給它
        result.then(resolve_next, reject_next);
      } else {
        //如果result是其他對象,則作爲參數傳給resolve_next
        resolve_next(result);
      }
    }
    self.resolveFunc = resolveFuncWrap;
    self.rejectFunc = rejectFuncWrap;
  })
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章