Learn JavaScript
❯ async.fetch

Fetching Data with fetch() in JavaScript

$concept

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.

$how it works
1

fetch fulfills on HTTP errors

404/500 resolve normally — only network failures reject. Always check response.ok before parsing.

2

Parse bodies with await

await res.json() / .text() / .blob() — second async step after the headers arrive.

3

Configure requests

fetch(url, {method: "POST", headers: {...}, body: JSON.stringify(data)}) — options object drives everything.

4

Cancel and time out

AbortController signals cancellation; timeouts race fetch against delayReject manually.

$example
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();
}
Output
(returns parsed user object; throws Error("HTTP 404") when missing)
1fetch resolves once headers arrive — body still pending.
2The ok check converts HTTP errors into thrown Errors (fetch won't do it).
3res.json() parses the body — two awaits, two failure axes, both handled.
$use cases
GET/POST JSON APIs with ok-checks plus try/catch
AbortController cancellation for stale requests and unmounts
Manual timeout races around fetch calls
Identical fetch code shared between browser and Node 18+

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.