Promise.all() Polyfill

The Promise.all() accepts an array of promises and returns a promise that resolves when all of the promises in the array are fulfilled or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

Promise.allPolyfill = (promises) => {
  const results = [];
  let promisesCompleted = 0;

  return new Promise((resolve, reject) => {
    promises.forEach((promise, promiseIndex) => {
      promise
        .then((val) => {
          results[promiseIndex] = val;
          promisesCompleted += 1;
          if (promisesCompleted === promises.length) {
            resolve(results);
          }
        })
        .catch((error) => reject(error));
    });
  });
};

Example

function task(time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (time < 3000) {
        reject("Rejected");
      } else {
        resolve(time);
      }
    }, time);
  });
}

const taskList = [task(5000), task(3000), task(4000)];

Promise.allPolyfill = (promises) => {
  const results = [];
  let promisesCompleted = 0;

  return new Promise((resolve, reject) => {
    promises.forEach((promise, promiseIndex) => {
      promise
        .then((val) => {
          results[promiseIndex] = val;
          promisesCompleted += 1;
          if (promisesCompleted === promises.length) {
            resolve(results);
          }
        })
        .catch((error) => reject(error));
    });
  });
};

Promise.allPolyfill(taskList)
  .then((results) => {
    console.log(results);
  })
  .catch((err) => {
    console.log(err);
  });