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
Fetch with timeout and status check
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)
  }
}
Timeouts should clean up their own timer too.
Fetch outcomes
SituationFetch behaviorYour code should
2xx responsePromise fulfillsParse expected body
404/500 responsePromise fulfillsCheck response.ok/status
Network/CORS failurePromise rejectsCatch/translate error
AbortPromise rejectsHandle cancellation separately
Sources
  • MDN JavaScript Guide and ReferenceFetch API and AbortController
  • The Modern JavaScript TutorialNetwork requests
  • Node.js Documentation and Learn Node.jsFetching data with Node.js