JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Prev

Learn the concept

Promises & Async/Await

javascript
senior
async

How would you implement Promise.all and Promise.race from scratch?

promise
async
polyfill
implementation
concurrency
interview-coding
Quick Answer

Promise.all takes an iterable of promises and returns a single promise that resolves with an array of all results (preserving order) or rejects with the first rejection. Promise.race returns a promise that settles with the first promise to settle, whether fulfilled or rejected.

Detailed Explanation

Implementing Promise combinators from scratch is a common interview question at companies like Swiggy, where Promise.race polyfill has been confirmed in online assessments. These implementations test understanding of Promise internals, iteration, and concurrent resolution patterns.

Promise.all

Behavior:

  • Takes an iterable (not just arrays) of values/promises
  • Returns a single Promise that resolves when all inputs resolve
  • Result array preserves the original order (not completion order)
  • Fails fast — rejects immediately on the first rejection
  • If the iterable is empty, resolves immediately with []
  • Non-promise values are treated as already-resolved promises

Key Implementation Details:

  • Use a counter to track how many promises have resolved (don't use results.length since array indices can be set out of order)
  • Use Promise.resolve(item) to wrap non-promise values
  • Store results by index to maintain order despite async completion

Promise.race

Behavior:

  • Returns a promise that settles with the first promise to settle
  • Can resolve or reject depending on which promise settles first
  • If the iterable is empty, the returned promise never settles (stays pending forever)
  • Non-promise values are wrapped with Promise.resolve(), making them settle synchronously via microtask

Promise.allSettled

Behavior:

  • Waits for all promises to settle (no short-circuiting)
  • Returns array of { status: 'fulfilled', value } or { status: 'rejected', reason } objects
  • Never rejects (unless the iterable itself throws)

Promise.any

Behavior:

  • Resolves with the first fulfilled promise (ignores rejections)
  • Only rejects if all promises reject, with an AggregateError
  • Opposite of Promise.all in rejection behavior

Code Examples

Promise.all implementationJavaScript
function promiseAll(iterable) {
  return new Promise((resolve, reject) => {
    const items = Array.from(iterable);

    if (items.length === 0) {
      resolve([]);
      return;
    }

    const results = new Array(items.length);
    let resolvedCount = 0;

    items.forEach((item, index) => {
      Promise.resolve(item).then(
        (value) => {
          results[index] = value; // Preserve order
          resolvedCount++;

          if (resolvedCount === items.length) {
            resolve(results);
          }
        },
        (reason) => {
          reject(reason); // Fail fast on first rejection
        }
      );
    });
  });
}

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

promiseAll([
  fetch('/api/users'),
  fetch('/api/posts'),
  fetch('/api/comments'),
]).then(([users, posts, comments]) => {
  console.log('All loaded');
});

// Fail fast
promiseAll([
  Promise.resolve('ok'),
  Promise.reject('fail'),
  new Promise(() => {}), // Never settles
]).catch(console.log); // 'fail' — rejects immediately

Real-World Applications

Use Cases

Request Timeouts

Using Promise.race to implement fetch timeouts by racing the actual request against a timer promise, ensuring requests don't hang indefinitely.

Parallel Data Fetching

Using Promise.all to fetch multiple API endpoints concurrently and wait for all results before rendering a dashboard or page.

Mini Projects

Promise Concurrency Limiter

advanced

Build a function that runs promises with a maximum concurrency limit (e.g., process 100 URLs but only 5 at a time), combining all four combinator patterns.

Industry Examples

Node.js

Node.js uses Promise.all internally for parallel operations like Promise-based fs methods and test runner parallel execution.

Resources

MDN - Promise.all()

docs

MDN - Promise.race()

docs

Related Questions

How would you implement a simplified Promise from scratch?

senior
promise-impl

What are Promise.all, Promise.race, Promise.allSettled, and Promise.any, and when do you use each?

mid
async
Previous
How would you implement JSON.stringify from scratch?
Prev