当前位置:
首页
文章
前端
详情

一、手写源码之 Promise

版本一,构造函数

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)
})

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。