实现 Promise.all

实现 Promise.all

借助 async/await

Promise.all = async (promises) => {
  const results = [];
  
  for (p of promises) {
    results.push(await p);
  }

  return results;
}

不借助 async/await

Promise.all = (promises) => {
  let resolved = 0;
  let results = [];
  return new Promise((resolve, reject) => {
    for (let promise of promises) {
      promise
        .then((result) => {
          results.push(result);
          if (++resolved === promises.length) resolve(results);
        })
        .catch((e) => {
          reject(e);
        });
    }
  })
}

参考