AbortController with fetch
- Version
- es2025
- Review
- Draft
Summary#
AbortController creates a signal you can pass to fetch. Calling abort() cancels the request, and can also abort reading the response body if that read is still in progress.
Syntax#
const controller = new AbortController();
const request = fetch(url, { signal: controller.signal });
controller.abort();
await request.catch(onError);
Example#
const controller = new AbortController();
controller.abort();
try {
await fetch("data:text/plain,hello", { signal: controller.signal });
} catch (error) {
if (
typeof error !== "object" ||
error === null ||
!("name" in error) ||
error.name !== "AbortError"
) {
throw error;
}
console.log(error.name);
}
Expected output#
AbortError. The already-aborted signal makes the outcome deterministic. Node.js releases with experimental fetch can also print a warning to stderr.
Common mistakes#
Pass the controller's signal and handle the request's rejection when you abort. Check the rejection's name for compatibility with early Node.js fetch implementations. Create a new controller for each independent request because an aborted signal stays aborted. Cancellation cannot undo work a server has already performed.
Version applicability#
AbortController and fetch are Web APIs. Node.js added the global AbortController in 14.17.0 and 15.0.0. The complete example uses --experimental-fetch from 16.15.0 and 17.5.0 and runs without flags from 18.0.0. Save it as an .mjs file for ES2022 top-level await.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0