fetch JSON with error handling
`fetch` only rejects on network failure — a 404 or 500 still resolves. Always check `res.ok` yourself.
#fetch#async#http#json
javascript
async function getUser(id) {
const res = await fetch(`/api/users/${id}`, {
headers: { Accept: "application/json" },
});
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
return res.json();
}
// POST with a body
await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" }),
});Related
Promises and async patterns
Run independent work in parallel with `Promise.all`. Use `allSettled` when one failure shouldn't kill the batch, and `race`/`AbortController` for timeouts.
HTTP status codes worth memorizing
2xx succeeded, 3xx go elsewhere, 4xx the caller is wrong, 5xx the server is wrong. These are the ones that come up in real APIs.