promise源码2

const PENDING = "pending"

const FULLFILLED = "fullfilled"

const REJECTED = "rejected"

class NumoPromise {

  constructor(exector) {

    if (typeof exector !== 'function') throw Error('exector params must be a function')

    this.status = PENDING

    this.value = undefined

    this.reason = undefined

    const resolve = (value) => {

      if (this.status === 'pending') {

        queueMicrotask(() => {

          if (this.status !== PENDING) return

          this.status = FULLFILLED

          this.value = value

          console.log(value)

        })

      }

    }

    const reject = (reason) => {

      if (this.status === 'pending') {

        queueMicrotask(() => {

          if (this.status !== PENDING) return

          this.status = REJECTED

          this.reason = reason

          console.log(reason)

        })

      }

    }

    exector(resolve, reject)

  }

  then(successFn, failFn) {

    this.successFns = successFn

    this.failFns = failFn

    if (this.status === 'fullfilled') {

      successFn(this.value)

    }

    if (this.status === 'rejected') {

      failFn(this.reason)

    }

  }

}

/**

 * 解决1: 解决了NumoPromise中exector异步执行

 * 解决2: 加上了一个.then方法

 */

const np = new NumoPromise((resolve, reject) => {

  setTimeout(() => {

    reject('error')

  }, 3000)

})

np.then((value) => console.log(value), (reason) => console.log(reason))

console.log('先执行')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容