手动实现Promise的封装

什么是Promise

Promise 是异步编程的一种解决方案,使用Promise对象可以将异步操作以同步操作的流程表达出来,同时可以解决回调地狱的问题

  class Mypromise {
    constructor(executor){
      this.status = 'pedding' // 等待状态
      this.value = null // 成功或失败的参数
      // 存储待执行的事件队列
      this.fulfilledCallbacks = []
      this.rejectedCallbacks = []

      const that = this
      // 成功的方法
      function resolve(value){
        if(that.status === 'pedding'){
          that.status = 'resolved'
          that.value = value
          that.fulfilledCallbacks.forEach(myFun => myFun(that.value))
        }
      }

      // 失败的方法
      function reject(value){
        if(that.status === 'pedding'){
          that.status = 'rejected'
          that.value = value
          that.rejectedCallbacks.forEach(myFun => myFun(that.value))
        }
      }

      try {
        executor(resolve, reject)
      } catch (error) {
        reject(error)
      }

    }

    // 给Promise添加then方法
    then(onFulfilled, onRejected){
      if(this.status === 'pedding'){
        this.fulfilledCallbacks.push(() => {
          onFulfilled(this.value)
        })

        this.rejectedCallbacks.push(() => {
          onRejected(this.value)
        })

        if(this.status === 'resolved'){
          onFulfilled(this.value)
        }
        if(this.status === 'rejected'){
          onRejected(this.value)
        }
      }
    }

  }

  function fn(){
    return new Mypromise((resolve, reject) => {
      setTimeout(() => {
        if(Math.random() > 0.6){
          resolve(1)
        } else {
          reject(2)
        }
      }, 1000)
    })
  }

  // 测试
  fn().then((res) => {
    console.log('res', res) // res 1
  }, (err) => {
    console.log('err', err) // err 2
  })

以上是本人简写的一个Promise,如有其他小伙伴还有更好的建议欢迎评论区留言一起交流~~ 

猜你喜欢

转载自blog.csdn.net/Star_ZXT/article/details/127602877