手写 promise

function MyPromise(exctor) {
  this.state = 'pending';
  this.fillFulledResult = ''
  this.rejectReason = ''
  this.fullfilledList = []
  this.rejectList = []
  const  reslove =  (value) => {
    if (this.state == 'pending') {
      this.state = 'fullfilled'
      this.fillFulledResult = value
      this.fullfilledList.forEach((fn) => {
        fn(value)
      })
    }
  }
  const  reject = (value) => {
    if (this.state == 'pending') {
      this.state = 'rejected'
      this.rejectReason = value
      this.rejectList.forEach((fn) => {
        fn(value)
      })
    }
  }
  exctor(reslove, reject)
}

// promise是链式调用的,所以在then 方法里返回的是一个promise对象
MyPromise.prototype.then = function (onFullfilled, onReject) {
  let that = this;
  return new MyPromise((reslove, reject) => {
    switch (that.state) {
      case 'pending':
        that.fullfilledList.push(value => { 
          setTimeout(() => {
            try {
              const result = onFullfilled(value);
              reslovePromiseHandle(result)
          } catch (error) {
            reject(error)
          }
          }, 0);
        })
        that.rejectList.push(value => { 
          setTimeout(() => {
            try {
              const result = onReject(value);
              reslovePromiseHandle(result)
            } catch (error) {
              reject(error)
            }
          }, 0);
        })
        break
      case 'fullfilled':
        setTimeout(() => {
          try {
            const success = onFullfilled(that.fillFulledResult);
            reslovePromiseHandle(success)
          } catch (error) {
            reject(error)
          }
        }, 0);
      
      
        break
      case 'rejected':
        setTimeout(() => {
          try {
            const errorreason = onReject(that.rejectReason);
            reslovePromiseHandle(errorreason)
          } catch (error) {
            reject(error)
          }
        }, 0);
        break
    }
    function reslovePromiseHandle (result) { 
      if (result instanceof MyPromise) { 
        result.then(reslovePromiseHandle, reject)
        return 
      }
      reslove(result)
    }
  })
}

MyPromise.prototype.catch = function (onReject) { 
  return this.then(null , onReject)
}


new MyPromise((reslove, reject) => { 
  reslove(2)
}).then(res => { 
  console.log('+++',res)
  return res +'1111'
}).then(res => new MyPromise((reslove, reject) => { 
  console.log(res +'1111')
  reject('error' + res)
})).catch(error => { 
  console.log(error)
  return 'jhhhh'
}).then(res => { 
  console.log(res +'1111+catch')
})
//+++ 2
//211111111
//error21111
//jhhhh1111+catch
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容