2. Asynchronous JavaScript & Browser APIs
Production async/await, Error Handling, Promise.all & AbortController
Write resilient async frontend code: catch HTTP 404/500 errors from fetch(), run parallel requests with Promise.all vs allSettled, and cancel stale requests using AbortController.
- Handle HTTP 4xx/500 responses safely with res.ok checks and try/catch/finally
- Choose accurately between Promise.all, Promise.allSettled, and Promise.race
- Cancel stale in-flight requests and race conditions cleanly with AbortController
Knowing async/await syntax is step one. Knowing how to avoid silent 404 bugs, slow sequential waterfalls, and out-of-order race conditions when a user types quickly in a search box is what makes your frontend production-grade!
1. The #1 fetch() Gotcha: 404 and 500 Do NOT Throw!
Many developers wrap fetch() in try/catch assuming a 404 Not Found or 500 Internal Server Error jumps into catch. It does not! fetch() only rejects on network failure (offline, DNS failure, CORS block). Always check res.ok explicitly:
async function fetchJson(url, signal) {
const res = await fetch(url, { signal });
if (!res.ok) {
throw new Error("HTTP " + res.status + " while fetching " + url);
}
return res.json();
}2. Parallel Requests: Promise.all vs allSettled vs race
Promise.all([...])
Resolves when all succeed; fails fast on the first rejection.
Promise.allSettled([...])
Never short-circuits; returns fulfilled or rejected status per item.
Promise.race([...])
Settles with whichever Promise finishes first (great for timeouts).
Choose Promise.all when every request is required, Promise.allSettled for partial dashboards, and Promise.race for timeouts.
Never await independent requests one after another when they can run concurrently:
// Slow sequential waterfall (300ms + 300ms = 600ms):
const user = await fetchJson("/api/user");
const courses = await fetchJson("/api/courses");
// Fast parallel fetch (~300ms total!):
const [user, courses] = await Promise.all([
fetchJson("/api/user"),
fetchJson("/api/courses"),
]);Use Promise.allSettled() for dashboards with independent widgets where one failing widget shouldn't crash the whole page, and Promise.race() (or AbortSignal.timeout(5000)) to enforce timeouts!
3. Cancelling Stale Requests with AbortController
Suppose a user types "py", pauses, then types "python":
- Request 1 (
"py") is slow (800ms). Request 2 ("python") finishes in100ms. - Without cancellation, Request 1 arrives
700mslater and overwrites"python"results with stale"py"results!
Pass controller.signal into fetch(url, { signal }) and call controller.abort() before starting the newer request (ignoring err.name === "AbortError" in catch).
Try It Yourself in the Playground
Test AbortController cancellation + parallel Promise.allSettled() live in this interactive Web Sandbox:
Mini-Challenge: Why should try { ... } finally { setLoading(false); } wrap your await fetch(...) UI calls?
Quick Checkpoints
What happens when await fetch('/missing-page') receives an HTTP 404 response?
Which combinator lets all concurrent Promises finish and returns { status: 'fulfilled' | 'rejected', ... } for each without short-circuiting on the first failure?