海纳百川

手写Promise(简单)

2020-09-21  本文已影响0人  凛冬已至_123
class Promise2 {
  succeed = null
  fail = null
  state = 'pending' 

  constructor(fn) {
    fn(this.resolve.bind(this), this.reject.bind(this))
  }
  
  resolve(result) {
    setTimeout(() => {
      this.state = 'fulfilled' 
      this.succeed(result)
    })
  }

  reject(reason) {
    setTimeout(() => {
      this.state = 'rejected' 
      this.fail(reason)
    })
  }

  then(succeed, fail) {
    this.succeed = succeed
    this.fail = fail
  }
}
Promise2.all = function(arrP) {
  let list = []
  return new Promise2((resolve, reject) => {
    for(let i = 0; i < arrP.length; i++) {
      arrP[i].then( data=> {
        list[i] = data
        
        list.length === arrP.length && resolve(list)
      }, error => {
        !hasErr && reject(error)
        hasErr = true
      })
    }
  })
}
Promise2.rac=function(arrP){
  let hasVal = false
  let hasError = false
  return new Promise2((resolve, reject) => {
    for(let i = 0; i < arrP.length; i++) {
      arrP[i].then( data=> {
        !hasVal&&!hasError&& resolve(list)
        hasVal = true
      }, error => {
        !hasVal&&!hasError&& resolve(list)&& reject(error)
        hasError = true
      })
    }
  })
}
上一篇下一篇

猜你喜欢

热点阅读