手写 Promise.all

90 阅读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) })
    })
  })
}