Async JavaScript
Fetch, AbortController & Cancellation
Fetch returns a Promise for an HTTP response, and AbortController provides a standard cancellation signal for requests and other abort-aware APIs.
- Fetch resolves for HTTP error statuses
- Network failures reject the Promise
- AbortController communicates cancellation
- Cancellation is cleanup, not just optimization
- Timeouts are application policy
async function fetchJson(url, timeoutMs = 5000) {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
try {
const res = await fetch(url, { signal: controller.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.json()
} finally {
clearTimeout(timeoutId)
}
}| Situation | Fetch behavior | Your code should |
|---|---|---|
| 2xx response | Promise fulfills | Parse expected body |
| 404/500 response | Promise fulfills | Check response.ok/status |
| Network/CORS failure | Promise rejects | Catch/translate error |
| Abort | Promise rejects | Handle cancellation separately |