Implement Promise.all from scratch

MediumTechnical
MetaSoftware Engineer
256

Implement Promise.all in JavaScript without using the built-in method. Handle success and failure cases correctly.

1 Answer

178
Top Answer
function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      return reject(new TypeError('Argument must be an array'));
    }

    const results = [];
    let completedCount = 0;

    if (promises.length === 0) {
      return resolve(results);
    }

    promises.forEach((promise, index) => {
      // Wrap in Promise.resolve to handle non-promise values
      Promise.resolve(promise)
        .then(value => {
          results[index] = value;  // Maintain order
          completedCount++;

          if (completedCount === promises.length) {
            resolve(results);
          }
        })
        .catch(reject);  // Reject immediately on any failure
    });
  });
}

// Test
promiseAll([
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
]).then(console.log); // [1, 2, 3]

Key points:

  • Results must be in original order
  • Reject on first failure
  • Handle non-promise values with Promise.resolve()
  • Handle empty array
PromiseImplementer

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Meta

View all