手写promise

分析

对于promise的复现,我们得先考虑promise的使用。

  • 使用时可以进行new操作,那么可以用构造函数获取class来构建
  • 存在then方法
  • 可以调用resolve和reject方法
  • 有三种状态 pending、fulfilled、rejected
  • ……
class myPromise {
  static PENDING = 'pending';
  static FULFILLED = 'fulfilled';
  static REJECTED = 'rejected'
  constructor(func) {
    this.status = myPromise.PENDING
    this.result = null
    this.resovleCallbacks = []
    this.rejectCallbacks = []
    try {
      func(this.resolve.bind(this), this.reject.bind(this))
    }
    catch (error) {
      this.reject(error)
    }
  }
  resolve (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.FULFILLED
        this.result = result
        this.resovleCallbacks.forEach(fn => fn(result))
      }
    })
  }
  reject (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.REJECTED
        this.result = result
        this.rejectCallbacks.forEach(fn => fn(result))
      }
    })
  }
  then (onFulfilled, onRejected) {
    return new myPromise((resolve, reject) => {
      // then里面传递的两个参数必须为函数
      onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : () => { }
      onRejected = typeof onRejected === 'function' ? onRejected : () => { }
      if (this.status === myPromise.PENDING) {
        this.resovleCallbacks.push(onFulfilled)
        this.rejectCallbacks.push(onRejected)
      }
      if (this.status === myPromise.FULFILLED) {
        setTimeout(() => {
          onFulfilled(this.result)
        })
      }
      if (this.status === myPromise.REJECTED) {
        setTimeout(() => {
          onRejected(this.result)
        })
      }
    })

  }
}

let p = new myPromise((resolve, reject) => {
  resolve('成功了')
  // reject('失败了')
  // throw new Error('失败了')
})
p.then(res => {
  console.log('第一次执行')
})
  .then(res => {
    console.log('第二次执行', res)
  })
posted @ 2022-10-18 16:21  含若飞  阅读(17)  评论(0编辑  收藏  举报