Fetching Data with fetch() in JavaScript
fetch(url) returns a promise of the Response — check response.ok (network success ≠ HTTP success: 404 fulfills!), then await response.json()/text() for bodies. Options configure method, headers, and JSON bodies; AbortController cancels in-flight requests; errors split into network failures (reject) versus HTTP errors (fulfill with bad status — must check manually).
Node 18+ ships fetch natively, unifying browser/server HTTP. Timeouts need manual racing (no built-in timeout option), credentials/cookies need explicit modes, and every fetch deserves ok-checks plus try/catch — the two failure axes covered independently.
fetch fulfills on HTTP errors
404/500 resolve normally — only network failures reject. Always check response.ok before parsing.
Parse bodies with await
await res.json() / .text() / .blob() — second async step after the headers arrive.
Configure requests
fetch(url, {method: "POST", headers: {...}, body: JSON.stringify(data)}) — options object drives everything.
Cancel and time out
AbortController signals cancellation; timeouts race fetch against delayReject manually.
async function getUser(id) { let res = await fetch("https://api.example.com/users/" + id); if (!res.ok) throw new Error("HTTP " + res.status); return res.json();}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.