05-基本的Promise实现3(多次调用)

实现

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject)
  }

  status = PENDING
  value = undefined
  reason = undefined
  
  successCallback = []
  failCallback = []

  resolve = value => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    
    while(this.successCallback.length) this.successCallback.shift()(value)
  }

  reject = reason => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    
    while(this.failCallback.length) this.failCallback.shift()(reason)
  }
  
  then(successCallback, failCallback) {
    if (this.status === FULFILLED) {
      successCallback(this.value)
    } else if (this.status === REJECTED) {
      failCallback(this.reason)
    } else {
      this.successCallback.push(successCallback)
      this.failCallback.push(failCallback)
    }
  }
}

module.exports = MyPromise

测试

const MyPromise = require('./05-my-promise-multiple')

const promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功!')
  }, 2000)
  // reject('失败!')
})

promise.then(value => {
  console.log(111111, value)
}, reason => {
  console.log(222222, reason)
})

promise.then(value => {
  console.log(333333, value)
}, reason => {
  console.log(444444, reason)
})

promise.then(value => {
  console.log(555555, value)
}, reason => {
  console.log(666666, reason)
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容