手写 Promise

123 阅读1分钟

// 手写 Promiseclass Promise {  constructor(executor) {    this.status = 'pending'    this.value = undefined    this.reason = undefined    let resolve = value => {      if(this.status === 'pending') {        this.status = 'fulfilled'        this.value = value      }    }    let reject = reason => {      if(this.status === 'pending') {        this.status = 'rejected'        this.reason = reason      }    }    try {      executor(resolve, reject)    } catch (error) {      reject(error)    }  }  then(onFulfilled, onRejected) {    if(this.status === 'fulfilled') {      onFulfilled(this.value)    }    if(this.status === 'rejected') {      onRejected(this.reason)    }  }}