实现Promise

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)

          })

        })

      }

    })

  }

}

构造函数方式实现

未完待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值