FrontendInterviews.dev

Loading problem…

28. Promise.all Polyfill

Medium•

Implement your own version of Promise.all method. The Promise.all method takes an iterable of promises and returns a single promise that resolves when all of the input promises have resolved, or rejects with the reason of the first promise that rejects.

Requirements

1. Basic Functionality

  • Accept an iterable of promises (array, Set, etc.)
  • Return a Promise that resolves with an array of results
  • Preserve the order of results (results array matches input order)
  • Resolve only when all promises resolve

2. Error Handling

  • Reject immediately when any promise rejects (fail-fast behavior)
  • Reject with the reason of the first rejected promise
  • Prevent multiple rejections

3. Edge Cases

  • Handle empty iterable (should resolve with empty array)
  • Handle non-promise values (should wrap them with Promise.resolve)
  • Handle already settled promises
  • Support any iterable, not just arrays

Example Usage

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

// One promise rejects
promiseAll([
  Promise.resolve(1),
  Promise.reject('error'),
  Promise.resolve(3)
]).catch(console.log); // 'error'

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

// Empty array
promiseAll([])
  .then(console.log); // []

Constraints

  • Must handle any iterable (not just arrays)
  • Must preserve order of results
  • Must fail fast on first rejection
  • Must handle non-promise values
  • Must return a Promise
Accepted16/18|Acceptance Rate88.9%