美文网首页
05-基本的Promise实现3(多次调用)

05-基本的Promise实现3(多次调用)

作者: Phoenixing | 来源:发表于2021-06-08 00:38 被阅读0次

    实现

    const PENDING = 'pending'
    const FULFILLED = 'fulfilled'
    const REJECTED = 'rejected'
    
    class MyPromise {
      constructor(executor) {
        executor(this.resolve, this.reject)
      }
    
      status = PENDING
      value = undefined
      reason = undefined
      
      successCallback = []
      failCallback = []
    
      resolve = value => {
        if (this.status !== PENDING) return
        this.status = FULFILLED
        this.value = value
        
        while(this.successCallback.length) this.successCallback.shift()(value)
      }
    
      reject = reason => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        
        while(this.failCallback.length) this.failCallback.shift()(reason)
      }
      
      then(successCallback, failCallback) {
        if (this.status === FULFILLED) {
          successCallback(this.value)
        } else if (this.status === REJECTED) {
          failCallback(this.reason)
        } else {
          this.successCallback.push(successCallback)
          this.failCallback.push(failCallback)
        }
      }
    }
    
    module.exports = MyPromise
    

    测试

    const MyPromise = require('./05-my-promise-multiple')
    
    const promise = new MyPromise((resolve, reject) => {
      setTimeout(() => {
        resolve('成功!')
      }, 2000)
      // reject('失败!')
    })
    
    promise.then(value => {
      console.log(111111, value)
    }, reason => {
      console.log(222222, reason)
    })
    
    promise.then(value => {
      console.log(333333, value)
    }, reason => {
      console.log(444444, reason)
    })
    
    promise.then(value => {
      console.log(555555, value)
    }, reason => {
      console.log(666666, reason)
    })
    

    相关文章

      网友评论

          本文标题:05-基本的Promise实现3(多次调用)

          本文链接:https://www.haomeiwen.com/subject/irqdeltx.html