一、手写源码之 Promise

洪少 发表时间: 2020-09-09 17:21 阅读:80 收藏:0

版本一,构造函数

function MyPromise(fn = () => {}) {
  // const this = {}
  this.state = 'pending'
  this.value = undefined

  const resolve = (value) => {
    if (this.state === 'pending') {
      this.state = 'fulfilled'
      this.value = value
    }
  }
  const reject = (value) => {
    if (this.state === 'pending') {
      this.state = 'rejected'
      this.value = value
    }
  }

  this.then = (onFulfilled, onRejected) => {
    switch (this.state) {
      case 'fulfilled':
        onFulfilled(this.value)
        break
      case 'rejected':
        onRejected(this.value)
        break
      default:
        onRejected(this.value);
    }
  }

  try {
    fn(resolve, reject)
  } catch (e) {
    reject(e)
  }
}

版本二,class类

class MyPromise {
  constructor (fn) {
    this.state = 'pending'
    this.value = undefined
    let resolve = value => {
      if (this.state === 'pending') {
        this.state = 'fulfilled'
        this.value = value
      }
    }
    let reject = value => {
      if (this.state === 'pending') {
        this.state = 'rejected'
        this.value = value
      }
    }
    // 自动执行函数
    try {
      fn(resolve, reject)
    } catch (e) {
      reject(e)
    }
  }
  // then
  then(onFulfilled, onRejected) {
    switch (this.state) {
      case 'fulfilled':
        onFulfilled(this.value)
        break
      case 'rejected':
        onRejected(this.value)
        break
      default:
        onRejected(this.value);
    }
  }
}

实例化执行

new MyPromise((resolve, reject) => {
  console.log('in Promise...')
  resolve(111)
}).then((val) => {
  console.log('resolve', val)
}, (e) => {
  console.log('rejected', e)
})
收藏
评论区
发表评论