Bootstrap

手撕Promise之从0开始实现完整的Promise的对象-catch函数实现

var MyPromise = function (fn) {
  // 更新状态和值
  this.PromiseState = 'pending'
  this.PromiseResult = undefined
  // 定义then的回调函数
  this.thenCallback = undefined;
   // 定义catch的回调函数
   this.catchCallback = undefined;
  var _this = this;
  var resolve = function (value) {
    // 只能由pending改变
    if (_this.PromiseState === 'pending') {
      _this.PromiseState = 'fulfilled';
      _this.PromiseResult = value
         // 判断传入的是不是promise对象
    if (value instanceof MyPromise) {
      // 是promise对象,就在then回调中获得本次结果
      value.then((res)=>{
        if (_this.thenCallback) {
          _this.thenCallback(res)
        }
      })
    } else {
      // 异步执行then函数注册的回调
      setTimeout(() => {
        if (_this.thenCallback) {
          _this.thenCallback(value)
        }
      })
    }
    }
 
  }
  var reject = function (errValue) {
    if (_this.PromiseState === 'pending') {
      _this.PromiseState = 'rejected';
      _this.PromiseResult = errValue;
      setTimeout(() => {
        if (_this.catchCallback) {
          _this.catchCallback(errValue)
        } else if (_this.thenCallback) {
          _this.thenCallback(errValue)
      } else{
        throw('catch is no defined')
      }
      })
    }
  }
  if (fn) {
    fn(resolve, reject)
  }
}

MyPromise.prototype.then = function (callback) {
  var _this = this;
  // 返回一个promise,可以再次执行then函数
  return new MyPromise((resolve, reject) => {

    _this.thenCallback = (value) => {
      if (_this.PromiseState === 'rejected') {
        reject(value)
      } else {
        var lastcallback = callback(value)
        if (lastcallback instanceof MyPromise && lastcallback.PromiseState === 'rejected') {
          lastcallback.catch((errValue) => {
            reject(errValue)
          })
        } else {
          resolve(lastcallback)
        }
        console.log(lastcallback);
     
      }
    }
  })
}
MyPromise.prototype.catch = function (callback) {
  var _this = this;
   // catch
  return new MyPromise((resolve, reject) => {
    _this.catchCallback = (err) => {
      var lastcallback = callback(err)
      resolve(lastcallback)
    }
  })
}
MyPromise.resolve=(res)=>{
 return  new MyPromise((resolve,reject)=>{
  resolve(res)
 })
}
MyPromise.reject=(res)=>{
 return  new MyPromise((resolve,reject)=>{
  reject(res)
 })
}

;