Skip to the content

Lesson 84 of 296

Your own Promise.all, sleep and retry

On this page

Task 1: sleep

"Write sleep(ms) that returns a promise which resolves after ms milliseconds."

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

await sleep(1000);
console.log("1 second later");

setTimeout calls resolve after the delay, which fulfils the promise. Useful for retries, tests and demos. It does not block the thread; only the async function that awaits it pauses.

Task 2: Promise.all

"Implement Promise.all without using it."

Rules of the real Promise.all (Lesson 71):

  1. Takes an iterable of values or promises.
  2. Returns a promise.
  3. Fulfils with an array of results in the input order, not the finishing order.
  4. Rejects as soon as any input rejects.
  5. Fulfils immediately with [] for an empty input.
  6. Non-promise values are treated as already fulfilled.
function promiseAll(items) {
  return new Promise((resolve, reject) => {
    const list = Array.from(items);
    const results = new Array(list.length);
    let completed = 0;

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

    list.forEach((item, index) => {
      Promise.resolve(item).then((value) => {
        results[index] = value;
        completed++;
        if (completed === list.length) {
          resolve(results);
        }
      }, reject);
    });
  });
}

Key details:

  • results[index] = value, not results.push(value). Push would store results in finishing order.
  • A counter decides when we are done, not results.length (the array has its full length from the start).
  • Promise.resolve(item) turns plain values into promises.
  • reject is passed directly as the error handler. The first rejection settles the promise; later calls are ignored (Lesson 69).

Test it

await promiseAll([sleep(30).then(() => 1), 2, Promise.resolve(3)])     [1, 2, 3]
await promiseAll([])                                                     []
await promiseAll([1, Promise.reject(new Error("x"))])                   rejects with Error("x")

Bonus: Promise.allSettled

Same structure, but never reject: store { status: "fulfilled", value } or { status: "rejected", reason } for each, and resolve when all are settled.

Task 3: retry

"Write retry(fn, times) that calls an async function and retries if it fails, up to times attempts."

Network calls can fail for temporary reasons. Retrying, with a growing delay, often succeeds.

async function retry(fn, times = 3, delayMs = 200) {
  let lastError;
  for (let attempt = 1; attempt <= times; attempt++) {
    try {
      return await fn(attempt);
    } catch (error) {
      lastError = error;
      if (attempt < times) {
        await sleep(delayMs * 2 ** (attempt - 1));
      }
    }
  }
  throw new Error(`Failed after ${times} attempts`, { cause: lastError });
}
  • return await inside try is important: without await, a rejection would not be caught by this catch.
  • Exponential backoff: the waits double each time: 200 ms, 400 ms, 800 ms. This gives a struggling server time to recover.
  • After the last attempt, throw a clear error that keeps the original as cause (Lesson 72).

Usage:

const user = await retry(() => fetchJson("/api/user/1"), 4, 300);

Follow-up questions

  • "Should every error be retried?" No. Retry temporary problems (network errors, timeouts, HTTP 429, 502, 503, 504). Do not retry errors that will fail again (400 bad request, 401, 404).
  • "What is jitter?" Adding a small random amount to each delay so thousands of clients do not all retry at the same moment.
  • "Is it safe to retry a payment?" Only if the request is idempotent, meaning running it twice has the same effect as once. Payment APIs use idempotency keys for this (Part 15).

Common mistakes

  • Promise.all: using push, or checking results.length.
  • Promise.all: forgetting the empty-array case, so it never resolves.
  • Retry: return fn() without await inside try.
  • Retry: retrying immediately with no delay, or retrying non-temporary errors.

How to say it in an interview

"sleep wraps setTimeout in a promise. For Promise.all I return a new promise, wrap each input with Promise.resolve, store each result at its original index and count completions, resolving when the count equals the input length, passing reject directly so the first failure rejects; an empty input resolves immediately. For retry I loop with try-catch, return await the function so rejections are caught, back off exponentially between attempts, and after the last attempt throw an error with the original as the cause. I only retry transient errors and idempotent operations."

Key words

WordMeaning
sleepA promise that resolves after a delay
RetryTrying a failed operation again
Exponential backoffDoubling the wait between retries
JitterRandom variation added to retry delays
Transient errorA temporary error that may succeed if retried
IdempotentSafe to repeat: doing it twice has the same effect as once

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.