Module 3: Promises

JavaScript runs on one thread, so anything slow β€” network calls, file reads, database queries β€” must be asynchronous. Promises are the standard way to represent "a value that will arrive later." Master them and async/await becomes trivial.

3.1 First: The Event Loop

Understanding when async code runs is half the battle. JavaScript executes in this order:

  1. Synchronous code runs top to bottom on the call stack.
  2. Microtasks (Promise callbacks, queueMicrotask) run as soon as the stack is empty β€” all of them, before anything else.
  3. Macrotasks (setTimeout, setInterval, I/O) run one at a time, with all microtasks drained between each.
console.log("1");                                  // sync
setTimeout(() => console.log("2"), 0);             // macrotask
Promise.resolve().then(() => console.log("3"));    // microtask
console.log("4");                                  // sync

// Output: 1, 4, 3, 2
// Sync first β†’ then microtasks (3) β†’ then macrotasks (2)
πŸ’‘ The interview litmus test

If you can explain why that prints 1, 4, 3, 2, you genuinely understand async JavaScript. Practice more of these puzzles on the Interview page, and watch Jake Archibald's talk "In the Loop" β€” the best 35 minutes you'll spend on this topic.

3.2 What a Promise Is

A Promise is an object representing an eventual result. It's always in exactly one of three states, and it settles exactly once β€” it can never change its mind afterward.

StateMeaningThen what?
pendingWork in progressWill transition once
fulfilledSucceeded with a value.then handlers run
rejectedFailed with a reason (an Error).catch handlers run
// Creating a Promise (you mostly CONSUME them, but know the mechanics)
function wait(ms) {
  return new Promise((resolve, reject) => {
    if (ms < 0) return reject(new Error("time cannot be negative"));
    setTimeout(() => resolve(`waited ${ms}ms`), ms);
  });
}

// Consuming it
wait(500)
  .then(msg => console.log(msg))          // on fulfillment
  .catch(err => console.error(err))       // on rejection
  .finally(() => console.log("cleanup")); // always runs

// Instant promises β€” handy for testing and defaults
Promise.resolve(42);
Promise.reject(new Error("nope"));

3.3 Chaining β€” the Core Insight

.then() always returns a new Promise. Whatever you return inside a handler becomes the next link's input. If you return a Promise, it's automatically unwrapped before the next .then runs. This is what lets you write flat chains instead of nested callbacks.

fetch("https://api.github.com/users/octocat")
  .then(res => res.json())            // returns a Promise β†’ auto-unwrapped
  .then(user => {
    console.log(user.name);
    return fetch(user.repos_url);     // chain a dependent request
  })
  .then(res => res.json())
  .then(repos => console.log(`${repos.length} repos`))
  .catch(err => console.error("Any step above failed:", err))
  .finally(() => console.log("done either way"));
// ❌ Callback-hell shape β€” never do this with promises:
fetch(url).then(res => {
  res.json().then(user => {
    fetch(user.repos_url).then(res2 => {   // nesting defeats the purpose!
      ...
    });
  });
});

// βœ… Return the inner promise and stay flat (previous example).

3.4 Error Handling

A rejection travels down the chain, skipping every .then, until it hits a .catch. After a .catch handles it, the chain is "healthy" again and continues fulfilled.

fetchUser(id)
  .then(user => enrich(user))       // skipped if fetchUser rejects
  .catch(err => {
    console.warn("Falling back to guest:", err.message);
    return GUEST_USER;              // recover β†’ chain continues fulfilled
  })
  .then(user => render(user));      // runs with real OR guest user

// Throwing inside .then also rejects the chain:
fetch("/api/data")
  .then(res => {
    if (!res.ok) throw new Error(`HTTP ${res.status}`);  // fetch does NOT
    return res.json();                                    // auto-reject on 404!
  })
  .catch(handleError);
🚫 The unhandled rejection

A rejected Promise with no .catch crashes Node processes (unhandledRejection) and pollutes browser consoles. Every chain you create must end in a .catch (or be awaited inside try/catch). Backend rule of thumb: whoever creates the promise chain owns its errors.

3.5 The Combinators: Running Promises Together

MethodResolves when…Rejects when…Use for
Promise.allALL fulfill (array of values, in order)ANY rejects (fail-fast)Parallel required work
Promise.allSettledALL settle β€” never rejectsneverBatch jobs where partial failure is OK
Promise.raceFIRST to settle (win or lose)first settle is a rejectionTimeouts, fastest-source
Promise.anyFIRST to fulfillALL reject (AggregateError)Redundant mirrors/fallbacks
const [user, posts, comments] = await Promise.all([
  fetch("/api/user").then(r => r.json()),
  fetch("/api/posts").then(r => r.json()),
  fetch("/api/comments").then(r => r.json()),
]);   // total time = SLOWEST request, not the sum ⚑

// allSettled β€” inspect each outcome:
const results = await Promise.allSettled(urls.map(u => fetch(u)));
const ok     = results.filter(r => r.status === "fulfilled").map(r => r.value);
const failed = results.filter(r => r.status === "rejected").map(r => r.reason);

// race β€” the classic timeout pattern:
function withTimeout(promise, ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms)
  );
  return Promise.race([promise, timeout]);
}
await withTimeout(fetch("/slow-api"), 5000);

3.6 Promisifying Callbacks (backend essential)

Older Node APIs use error-first callbacks. Wrapping them in Promises is a rite of passage β€” and still needed for many libraries.

// Old style: fs.readFile(path, cb(err, data))
function readFilePromise(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, "utf8", (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

// Node has a built-in helper:
import { promisify } from "node:util";
const readFile = promisify(fs.readFile);

// ...and most core modules now ship promise versions:
import { readFile as rf } from "node:fs/promises";

Common Beginner Mistakes

  • Forgetting to return inside .then β€” the next link gets undefined and timing breaks silently.
  • Nesting .then inside .then instead of returning and chaining flat.
  • Assuming fetch rejects on HTTP errors. It only rejects on network failure; a 404 fulfills! Always check res.ok.
  • Creating promises with the new Promise anti-pattern around something that already returns a promise: new Promise(res => fetch(url).then(res)) β€” just use fetch(url).
  • Believing .then makes code wait. The line after a chain runs immediately; only the callbacks are deferred.
  • Running dependent-free work sequentially instead of with Promise.all.

Exercises

Easy 1. Predict the output
console.log("A");
Promise.resolve("B").then(console.log);
setTimeout(() => console.log("C"), 0);
Promise.resolve().then(() => {
  console.log("D");
  setTimeout(() => console.log("E"), 0);
});
console.log("F");
Solution

A, F, B, D, C, E. Sync first (A, F). Then all microtasks in queue order (B, D β€” and D schedules macrotask E). Then macrotasks in order scheduled (C, then E).

Easy 2. Build wait(ms)

Implement wait(ms) returning a Promise, then chain it: log "one" β†’ wait 1s β†’ log "two" β†’ wait 1s β†’ log "three". No nesting allowed.

Solution
const wait = ms => new Promise(res => setTimeout(res, ms));

console.log("one");
wait(1000)
  .then(() => {
    console.log("two");
    return wait(1000);      // ← RETURN keeps the chain waiting
  })
  .then(() => console.log("three"));
Medium 3. Implement retry(fn, attempts)

Write retry(fn, attempts) β€” call the promise-returning fn; if it rejects, try again, up to attempts total tries. Resolve with the first success; reject with the last error.

Solution
function retry(fn, attempts) {
  return fn().catch(err => {
    if (attempts <= 1) throw err;          // out of tries β†’ propagate
    return retry(fn, attempts - 1);        // recurse; returned promise chains
  });
}

// Usage:
retry(() => fetch("/flaky-api").then(r => {
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
  return r.json();
}), 3).then(console.log).catch(console.error);

Bonus: add exponential backoff by chaining wait(2 ** attempt * 100) before retrying.

Medium 4. First mirror wins

Given two mirror URLs of the same API, fetch from both and use whichever succeeds first β€” falling through if one fails. Which combinator, and why not race?

Solution
const data = await Promise.any([
  fetch(mirror1).then(r => r.ok ? r.json() : Promise.reject(r.status)),
  fetch(mirror2).then(r => r.ok ? r.json() : Promise.reject(r.status)),
]);

race settles with the first result even if it's a rejection β€” a fast failure would kill you. any waits for the first success and only rejects if all fail.

Hard 5. Implement promiseAll from scratch

Write your own promiseAll(promises) without using Promise.all. Preserve result order, fail fast on first rejection. (Extremely common interview question.)

Solution
function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    const results = new Array(promises.length);
    let remaining = promises.length;
    if (remaining === 0) return resolve(results);

    promises.forEach((p, i) => {
      Promise.resolve(p).then(value => {     // Promise.resolve handles raw values
        results[i] = value;                  // index, not push β†’ preserves order
        if (--remaining === 0) resolve(results);
      }, reject);                            // any rejection β†’ fail fast
    });
  });
}
Project Module project: API Race Dashboard

Build a page that fetches the same resource from JSONPlaceholder and a second mirror, shows a live "race" of which responds first, adds a 3s timeout with race, retries failures, and displays per-request status with allSettled. Full spec on the Projects page.

Interview Questions from This Module

What are the states of a Promise?

Pending, fulfilled, rejected. It starts pending and settles exactly once β€” transitions are one-way and permanent. "Settled" means fulfilled or rejected.

Difference between Promise.all and Promise.allSettled?

all is fail-fast: one rejection rejects the whole thing and you lose the other results. allSettled always fulfills with a status report per promise ({status, value|reason}) β€” use it when partial failure is acceptable.

What are microtasks vs macrotasks?

Microtasks (Promise callbacks) run immediately after the current synchronous code, and the whole microtask queue is drained before the next macrotask. Macrotasks (setTimeout, I/O) run one per event-loop turn. That's why Promise.resolve().then() always beats setTimeout(fn, 0).

Does fetch() reject on a 404?

No β€” fetch only rejects on network-level failures (DNS, offline, CORS). HTTP error statuses fulfill normally; you must check response.ok or response.status yourself. Libraries like axios do reject on HTTP errors, which is why people get confused.