fetch and AbortController
fetch() provides a Promise-based interface for HTTP requests. It resolves when a response is available, including many HTTP error status codes; a 404 or 500 does not automatically reject the Promise. Applications should inspect response.ok or status explicitly.
AbortController can cancel fetch operations and other APIs that support AbortSignal.
Fetch with Cancellation
const controller = new AbortController();
async function load() {
const response = await fetch('/api/users', {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
load().catch(console.error);
// Cancel when appropriate
controller.abort();💡 The AbortSignal connects the controller to fetch. Aborting causes the request Promise to reject with an abort-related error.
Key Takeaways
- fetch does not reject merely because the HTTP status is 4xx or 5xx.
- Check response.ok or response.status.
- AbortController provides cooperative cancellation for supported APIs.
Knowledge Check
Does fetch reject its Promise automatically for a 404 response?