美文网首页海纳百川
手写Promise(简单)

手写Promise(简单)

作者: 凛冬已至_123 | 来源:发表于2020-09-21 22:50 被阅读0次
    • Promise
    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
      }
    }
    
    • Promise.all
    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
          })
        }
      })
    }
    
    • Promise.race
    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
          })
        }
      })
    }
    

    相关文章

      网友评论

        本文标题:手写Promise(简单)

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