Promise

特点

  1. 默认会传入一个executor函数,这个是立即执行的
  2. 这个executor函数有两个默认参数,一个resolve,一个reject
  3. promise会有三个状态,分别是pending,fulfilled,rejected
  4. 默认状态是PENDING,并且从一个状态变成另外一个状态就不可更改了
  5. 有一个then方法,会有两个回调函数,第一个是成功的,第二个是失败的回调
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class Promise {
  constructor(executor) {
    this.value = ''
    this.reason = ''
    this.status = PENDING
    this.onFulfilledCBArr = []
    this.onRejectedCBArr = []
    executor(resolve.bind(this), reject.bind(this))
    function resolve(params) {
      this.status = FULFILLED
      this.value = params
      this.onFulfilledCBArr.forEach(fn => fn()) //这里用到了一个发布订阅的设计模式
    }
    function reject(params) {
      this.status = REJECTED
      this.reason = params
      this.onRejectedCBArr.forEach(fn => fn())
    }
  }
  then(onFulfilledCB, onRejectedCB) {
    if (this.status === FULFILLED) {
      onFulfilledCB(this.value)
    }
    if (this.status === REJECTED) {
      onRejectedCB(this.reason)
    }
    if (this.status === PENDING) {
      this.onFulfilledCBArr.push(() => {
        onFulfilledCB(this.value)
      })
      this.onRejectedCBArr.push(() => {
        onRejectedCB(this.reason)
      })
    }
  }

}
Last modification:December 6th, 2020 at 11:47 pm
If you think my article is useful to you, please feel free to appreciate