手写一个promise

2018-11-22  本文已影响15人  lmmy123
// 声明三种状态机
const STATUS = {
  PENDING: 0,
  FULFILLED: 1,
  REJECTED: 2
}

function Promise(exector){
  this.status = STATUS.PEDNDING
  // resolve返回的数据
  this.resolveData = null
  // reject返回的数据
  this.rejectData = null
  // 缓存成功回调的函数
  this.onFulfilledList = []
  // 缓存失败回调的函数
  this.onRejectedList = []
  let self = this;
  // 成功时执行
  function onResolve(resolveData){
    if(self.status === STATUS.PENDING){
      self.resolveData = resolveData
      self.status = STATUS.FULFILLED
      self.onFulfilledList.forEach(fn=>fn()) 
    }
  }
  //失败时执行
  function onReject(rejectData ){
      if(self.status === STATUS.PENDING){
      self.rejectData = rejectData
      self.status = STATUS.REJECTED
      self.onRejectedList.forEach(fn=fn())
    }
  }
  try {
    exector(onResolve, onReject)
  }catch(e){
    onReject(e)
  }
}

// 添加then 方法
Promise.prototype.then = function(onSucess, onError){
  let self = this
  if(this.status === STATUS.FULFILLED){
    onSucess(self.resolveData)
  }
  if(this.status === STATUS.REJECTED){
    onError(self.rejectData)
  }
  // 如果异步执行则为pending 状态
  if(this.status === STATUS.PENDING){
    // 保存回调函数
    this.onFulfilledList.push(()=>{
      onSucess(self.resolveData)
    })
    this.onRejectedList.push(()=>{
      onError(self.rejectData)
    })
  }
}
上一篇下一篇

猜你喜欢

热点阅读