首页 > 其他分享 >实现Promise

实现Promise

时间:2023-03-14 15:24:40浏览次数:30  
标签:status resolve 实现 CPromise value reason Promise reject

Promise 是异步的一种解决方案,有reject、resolve、then、catch、all、finally等方法。网上有很多关于Promise的优秀文章,深入浅出,多看看它们的原理和使用会茅塞顿开,但是最重要的还是自己动手敲,即使你只实现一部分,剩下的就能举一反三。

类的方式实现

class CPromise {

  constructor(exector) {

    this.status = 'pending'// 初始状态为pending

    this.value = null// 成功的值

    this.reason = null// 失败的原因

    this.onFulfilledCallbacks = []//成功的回调函数数组

    this.onRejectdCallbacks = []//失败的回调函数数组

    let resolve = value => {

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

        this.status = 'fulfilled'

        this.value  = value

        this.onFulfilledCallbacks.forEach(fn => fn())//调用成功的回调函数

      }

    }

    let reject = reason => {

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

        this.status = 'reject'

        this.reason = reason

        this.onRejectdCallbacks.forEach(fn => fn())//调用失败的回调函数

      }

    }

    try{

      exector(resolve, reject)

    }catch(error) {

      reject(error)

    }

  }

  


  then(onFulfilled, onRejected){

    return new CPromise((resolve, reject) => {

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

        setTimeout(() => {

          const x = onFulfilled(this.value)

          x instanceof CPromise ? x.then(resolve, reject) : resolve(x)

        })

      }

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

        setTimeout(() => {

          const x = onRejected(this.reason)

          x instanceof CPromise ? x.then(resolve, reject) : resolve(x)

        })

      }

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

        this.onFulfilledCallbacks.push(() => {// 将成功的回调放入成功数组

          setTimeout(() => {

            const x = onFulfilled(this.value)

            x instanceof CPromise ? x.then(resolve, reject) : resolve(x)

          })

        })

        this.onRejectedCallbacks.push(() => { //将失败的回调函数放入失败数组

          setTimeout(() => {

            const x = onRejected(this.reason)

            x instanceof CPromise ? x.then(resolve, reject) : resolve(x)

          })

        })

      }

    })

  }

}

构造函数方式实现

未完待续。。。

标签:status,resolve,实现,CPromise,value,reason,Promise,reject
From: https://www.cnblogs.com/rain111/p/17215028.html

相关文章