Abortable fetch
The read-only signal property of the Request interface returns the AbortSignal associated with the request.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 66 | 16 | 57 | 12.1 | 66 | 12.2 | |
init_signal_parameter `init.signal` parameter | 66 | 16 | 57 | 11.1 | 66 | 11.3 |
1+Supported (version) Not supported ※Has note Sub-feature descriptions sourced from MDN Web Docs (CC BY-SA 2.5)
Syntax
JAVASCRIPT
// Create a new abort controller
const controller = new AbortController();
// Create a request with this controller's AbortSignal object
const req = new Request("/", { signal: controller.signal });
// Add an event handler logging a message in case of abort
req.signal.addEventListener("abort", () => {
console.log("abort");
});
// In case of abort, log the AbortSignal reason, if any
fetch(req).catch(() => {
if (req.signal.aborted) {
if (req.signal.reason) {
console.log(`Request aborted with reason: ${req.signal.reason}`);
} else {
console.log("Request aborted but no reason was given.");
}
} else {
console.log("Request not aborted, but terminated abnormally.");
}
});
// Actually abort the request
controller.abort(); Use cases
-
Using Abortable fetch
The read-only signal property of the Request interface returns the AbortSignal associated with the request.
Cautions
- May not be supported in older browsers.
Implementation notes
- Some APIs require a secure context (HTTPS) or user activation. Check the requirements before use.