Skip to content
Write a polyfill for promise.all()

Write a polyfill for promise.all()

promise.all takes an iterable (objects that can be iterated over, usually array) as an input and returns a single promise which is resolved when all the promises in the list are resolved. Or it rejects immediately even if one of the input promises is rejected or throws an error.

🔗 Promise.all 🟡 Medium 🧩 Pattern – Promises

Related: Execute Asynchronous Functions in Parallel – 2721 | Matrixread

The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input’s promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input’s promises rejects, with this first rejection reason.

Source: Promise.all() – JavaScript | MDN

promise.all

/**
 * @param {Array} iterable
 * @return {Promise<Array>}
 */
export default function promiseAll(iterable) {
  return new Promise((resolve, reject) => {
    const results = new Array(iterable.length);
    let unresolved = iterable.length;
    // Handle empty array
    if (unresolved === 0) {
      resolve(results);
      return;m
    }
    // We wait for each promise to resolve and store resolvedValue in the same order
    iterable.forEach(async (item, index) => {
      try {
        const resolvedValue = await item;
        results[index] = resolvedValue;
        unresolved -= 1;
        if (unresolved === 0) {
          resolve(results);
        }
      } catch (error) {
        reject(error);
      }
    });
  });
Code language: JavaScript (javascript)
Back to Top