FossilsðŸ’ŧ CodingImplement Promise.all
ðŸĢHatchlingJavaScriptAsyncPromises

Implement Promise.all

Building Promise.all from scratch tests your understanding of async coordination and error handling.

Implement Promise.all

This question tests whether you understand Promise mechanics beyond just .then() and async/await.

Implementation

function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    const results = [];
    let settled = 0;
    const items = Array.from(promises);
 
    if (items.length === 0) {
      resolve([]);
      return;
    }
 
    items.forEach((promise, index) => {
      Promise.resolve(promise).then(
        (value) => {
          results[index] = value;
          settled++;
          if (settled === items.length) resolve(results);
        },
        (reason) => {
          reject(reason);
        }
      );
    });
  });
}

Key Details to Discuss

  1. Order preservation — results must match input order, not resolution order
  2. Non-promise values — Promise.resolve() wraps them correctly
  3. Empty array — should resolve immediately with []
  4. First rejection wins — any rejection short-circuits the entire promise
  5. Iterable input — Array.from() handles any iterable

Follow-Up: Promise.allSettled

function promiseAllSettled(promises) {
  return new Promise((resolve) => {
    const results = [];
    let settled = 0;
    const items = Array.from(promises);
 
    if (items.length === 0) {
      resolve([]);
      return;
    }
 
    items.forEach((promise, index) => {
      Promise.resolve(promise).then(
        (value) => {
          results[index] = { status: 'fulfilled', value };
          settled++;
          if (settled === items.length) resolve(results);
        },
        (reason) => {
          results[index] = { status: 'rejected', reason };
          settled++;
          if (settled === items.length) resolve(results);
        }
      );
    });
  });
}

When to Use Which

MethodBehaviorUse Case
Promise.allFail fast on first rejectionAll-or-nothing operations
Promise.allSettledWait for all, never rejectsIndependent operations with graceful degradation
Promise.raceFirst to settle winsTimeouts, fastest source
Promise.anyFirst fulfillment winsFallback data sources

The senior signal: knowing which Promise combinator to use for a given problem is more valuable than implementing them.