手写 Promise.all

57 阅读1分钟

要点:

  1. 知道要在 Promise 上写而不是在原型上写
  2. 知道 all 的参数(Promise 数组)和返回值(新 Promise 对象)
  3. 知道用数组来记录结果
  4. 知道只要有一个 reject 就整体 reject
Promise.myAll = function(list){
  const results = []
  let count = 0 
  return new Promise((resolve,reject) =>{ 
  list.map((item, index)=> { 
  item.then(result=>{
  results[index] = result
  count += 1 
  if (count >= list.length) { resolve(results)} 
  }, reason => reject(reason) ) 
  })
  })
  }