手写Promise.all

110 阅读1分钟

成品代码

Promise.myall = function(list){
  let results = []
  let count = 0
  return new Promise((resolve,reject) => {
    list.map( (promise,index) => {
      promise.then((r) => {
        results[index] = r
        count += 1
        if(count >= list.length){
          resolve(results)
        }
      },(reason) => {
        reject(reason)
      })
    })
  })
}

流程:

  1. 不能再 Promise 的原型上写。
Promise.myall = function(){
  
}
  1. 根据 Promise.all ,我们手写的 myall ,参数得是一个装着 Promise 的数组;因为myall成功了也要调用 promise,所以需要return 新的 promise。
Promise.myall = function(list){
  return new Promise((resolve,reject) => {
    list.map( (promise,index) => {
      promise.then((r) => {
        
      },() => {
        
      }) 
    })
  })
}
  1. 每个 Promise 成功的值需要加到一个数组里存储。
Promise.myall = function(list){
  let results = []
  let count = 0
  return new Promise((resolve,reject) => {
    list.map( (promise,index) => {
      promise.then((r) => {
        results[index] = r
        count += 1
        if(count >= list.length){
          resolve(results)
        }
      },() => {
        
      })
    })
  })
}
  1. 只要有一个失败就直接失败。
Promise.myall = function(list){
  let results = []
  let count = 0
  return new Promise((resolve,reject) => {
    list.map( (promise,index) => {
      promise.then((r) => {
        results[index] = r
        count += 1
        if(count >= list.length){
          resolve(results)
        }
      },(reason) => {
        reject(re)
      })
    })
  })
}