Promise.all Polyfill

PromisesPolyfillConcurrency

Implement a promiseAll function that mimics the behavior of Promise.all.

Function Signature:

const promiseAll = (promises) => {
  // Your implementation
};

Key Concepts:

  • Concurrent Execution: All Promises start executing immediately, not sequentially
  • Order Preservation: Results must match input order, regardless of which Promise completes first
  • Fail-Fast: The first rejection should immediately reject the entire operation

Examples

Example 1
Input
const promises1 = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
];

promiseAll(promises1)
  .then(val => console.log('Result:', val))
  .catch(err => console.error('Error:', err));
Output
Result: [1, 2, 3]
Explanation
All Promises resolve successfully. The result array maintains the same order as the input array.
Example 2
Input
const promises2 = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.reject('Error occurred')
];

promiseAll(promises2)
  .then(val => console.log('Result:', val))
  .catch(err => console.error('Error:', err));
Output
Error: Error occurred
Explanation
When any Promise rejects, the entire operation fails immediately with that error (fail-fast behavior).

Constraints

  • The input is an array of Promises or any values
  • Non-Promise values should be treated as already-resolved Promises
  • Empty arrays should resolve to an empty array
  • Results must maintain the input order

Notes

  • Use `Promise.resolve()` to convert non-Promise values
  • Track results by index to maintain order
  • Reject immediately when any Promise rejects (don't wait for others)

Hints

Read the full write-up for Promise.all Polyfill
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it