AbortSignal
AbortSignal represents an abort signal: whether it has been aborted and why. Pass it as the signal of fetch(), and as soon as it is aborted, the request is canceled.
AbortSignal can't be created with new: new AbortSignal() throws TypeError: AbortSignal cannot be constructed directly, use new AbortController(). You get one from these three places:
| Source | What you get |
|---|---|
controller.signal | Controlled by controller.abort() |
AbortSignal.timeout() | Aborts automatically after the given number of milliseconds |
AbortSignal.abort() | A signal already in the aborted state |
Inheritance: EventTarget → AbortSignal
Static methods
Returns a signal that is already aborted.
Returns a signal that aborts automatically after the given time. Use it to set a timeout on a request.
Instance properties
| Property | Description |
|---|---|
aborted read-only | Whether it has been aborted |
reason read-only | The reason for aborting |
Instance methods
Also inherits addEventListener(), removeEventListener(), and dispatchEvent() from EventTarget.
| Method | Description |
|---|---|
throwIfAborted() | Throws reason if aborted |
Events
| Event | When it fires |
|---|---|
abort | Fires once when aborted |
Examples
async function main() {
try {
await fetch('https://httpbin.org/delay/5', { signal: AbortSignal.timeout(300) });
} catch (err) {
console.log(err instanceof Error ? err.name : err);
}
}
main();Result: After 300 milliseconds the request is canceled, and it prints AbortError.
Note: When a request is canceled while in progress, what
fetch()andread()throw isn'tsignal.reasonbut a newAbortError. So afterAbortSignal.timeout()expires,signal.reason.nameis'TimeoutError', while thenameof the exception thrown byfetch()is'AbortError'. To tell whether a request was canceled, check whether the exception'snameis'AbortError'.
Differences from the web
- There is no
DOMException. The defaultreasonis anErrorwhosenameis'AbortError', and the timeoutreasonis anErrorwhosenameis'TimeoutError'. - When a request is canceled while in progress,
fetch()throwsAbortError, notsignal.reason. - There is no
AbortSignal.any()and noonabortproperty.
See also
AbortController: sends the abort instructionfetch()