手写Promise 核心功能

182 阅读1分钟
// Promise 基本功能实现
class MyPromise {
  //  定义常量
  static PENDING = 'pending'
  static FULFILLED = 'fulfilled'
  static REJECTED = 'rejected'
  constructor(executor) {  //executor函数执行器,实例化的时候会直接执行
    this.status = MyPromise.PENDING // 初始化状态
    this.result = undefined // 初始化结果
    this.resolveCallBacks = []  // 异步成功回调存储集合
    this.rejectCallBacks = [] // 异步失败回调存储集合
    try { 
      executor(this.resolve, this.reject)
    } catch (reason) {  // catch捕获错误,并直接调用reject方法
      this.reject(reason)
    }
  }
  resolve = value => { // 成功的方法,改变状态,赋值结果
      if (this.status === MyPromise.PENDING) { // 只有状态时pending 时才能执行下面的代码
        this.status = MyPromise.FULFILLED // 改变状态为成功
        this.result = value
        this.resolveCallBacks.forEach(callback => callback(value))  // 循环执行所有成功的异步回调
      }
  }
  reject = reason => {
      if (this.status === MyPromise.PENDING) {  // 只有状态时pending 时才能执行下面的代码
        this.status = MyPromise.REJECTED
        this.result = reason
        this.rejectCallBacks.forEach(callback => callback(reason))   // 循环执行所有失败异步回调
      }
  }
  then(onFulfilled, onRejected) {  // then方法接受两个回调函数作为参数,第一个时成功的回调,第二个是失败的回调
      onFulfilled = typeof onFulfilled ==='function' ? onFulfilled :()=>{}  // 给参数设置默认值
      onRejected = typeof onRejected ==='function' ? onRejected :()=>{} // 给参数设置默认值
      if (this.status === MyPromise.FULFILLED) {  // 根据不同的状态执行不同的回调方法
        setTimeout(() => {      // 异步执行
          onFulfilled(this.result)
        })
      }
    if (this.status === MyPromise.REJECTED) { // 根据不同的状态执行不同的回调方法
        setTimeout(() => {  // 异步执行
          onRejected(this.result)
        })
      }
      if (this.status === MyPromise.PENDING) {  // 状态为pending的时候执行
        this.resolveCallBacks.push(onFulfilled)
        this.resolveCallBacks.push(onRejected)
      }
  }
}

let p = new MyPromise((resolve, reject) => {
  // resolve('最后--成功的结果')
  throw new Error('fail')
})
p.then(
  res => { console.log(res) },
  err=>{ console.log(err.message)}
)