04

Async & Networking

Promises, fetch, HTTP, caching

GoalMaster Promises as an engineering tool, understand what fetch actually does, and know the HTTP layer well enough to debug network problems.

Lessons

Promise internals

A Promise is an object representing a value not yet ready. It has three states: pending → fulfilled or rejected. Once settled it never changes.

js
const p = new Promise((resolve, reject) => {
  // async work...
  resolve(value);   // or reject(error)
});

p.then(v => ...).catch(e => ...).finally(() => ...);

.then returns a new Promise — the chain waits for it. If you return a Promise from .then, the chain flattens it automatically.

The fetch 404/500 trap

fetch only rejects on network failure (no connection, DNS fail, CORS block). HTTP error statuses like 404 and 500 fulfill with a response where res.ok === false.

js
// ❌ This catch NEVER fires on a 404 or 500
const data = await fetch('/api/user').then(r => r.json());

// ✅ Check res.ok manually
const res = await fetch('/api/user');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();

This is the #1 most common real fetch bug. Burn it in: check res.ok.

Promise combinators

Four tools for multiple promises:

  • Promise.all([...]) — waits for ALL, fails fast if ANY rejects. Runs in parallel.
  • Promise.allSettled([...]) — waits for ALL to settle (never rejects). Use when partial success is ok.
  • Promise.race([...]) — settles on the FIRST to settle. Use for timeouts.
  • Promise.any([...]) — fulfills on the FIRST success.
js
// ❌ Sequential — 900ms if each is 300ms
const a = await fetch('/a').then(r => r.json());
const b = await fetch('/b').then(r => r.json());
const c = await fetch('/c').then(r => r.json());

// ✅ Parallel — ~300ms
const [a, b, c] = await Promise.all([
  fetch('/a').then(r => r.json()),
  fetch('/b').then(r => r.json()),
  fetch('/c').then(r => r.json()),
]);

HTTP & Caching

Every fetch triggers: DNS → TCP handshake → TLS → HTTP request → response.

  • 200 OK, 201 Created, 204 No Content
  • 301/302 Redirect, 304 Not Modified (cached copy is still valid)
  • 400 Bad Request, 401 Unauthenticated, 403 Unauthorized, 404 Not Found, 429 Rate Limited
  • 500 Server Error, 503 Unavailable

HTTP Caching:

Cache-Control: max-age=3600    → serve from cache for 1hr, no request
Cache-Control: no-cache        → revalidate every time
ETag: "abc123"                 → fingerprint; if unchanged → 304 (empty body)

The fastest request is the one you never make. React Query/SWR implement this pattern at the application layer.

Challenges3

Write working code. Run to see output. Check to grade.

CH1
Promise chaining order
Medium

Predict the output:

js
console.log("A");
Promise.resolve()
  .then(() => { console.log("B"); return 42; })
  .then(v => console.log("C", v));
console.log("D");
JavaScript
CH2
Fix the sequential fetches
Hard

This loads 3 resources sequentially (~900ms if each takes 300ms). Rewrite it to load them in parallel using Promise.all and reduce the wait to ~300ms.

Use the provided mock fetch (already defined for you) that resolves after 1ms with fake data.

JavaScript
CH3
Which combinator?
Medium

You're loading a dashboard with 5 independent panels. If ONE fails, you still want to show the other 4.

Write code using the correct combinator that: 1. Runs 5 mock requests in parallel 2. Even if some fail, logs successful results 3. Logs how many succeeded

Use the mock below that randomly succeeds or fails.

JavaScript

References