AbortController
AbortController and AbortSignal cancel in-progress asynchronous
operations. Create a controller, pass its signal to an operation
(such as fetch()), and call abort() to cancel it. Every listener
of the signal’s abort event runs, and operations watching the signal
reject with the signal’s reason.
new AbortController()creates a controller.controller.signalis theAbortSignalto hand to operations.controller.abort(reason)fires the signal: theabortevent runs andsignal.abortedbecomestrue. The default reason is aDOMExceptionnamedAbortError.signal.abortedreports whether the signal has fired.signal.reasonis the abort reason, orundefinedbefore abort.signal.throwIfAborted()throws the reason when the signal has aborted.signal.addEventListener("abort", listener)(and the otherEventTargetmethods) register listeners; they can be removed withremoveEventListener().signal.onabortis a shorthand for anabortlistener.AbortSignal.abort(reason)creates an already-aborted signal.AbortSignal.timeout(milliseconds)creates a signal that aborts with aTimeoutErrorafter the delay.AbortSignal.any(signals)creates a signal that aborts when any of the input signals aborts.
Usage#
Cancelling a fetch after a timeout:
try {
const response = await fetch("https://httpbin.org/delay/5", {
signal: AbortSignal.timeout(5000),
});
console.log(await response.text());
} catch (err) {
if (err.name === "TimeoutError") {
console.log("request timed out");
}
}
Cancelling with your own reason:
const controller = new AbortController();
setTimeout(() => controller.abort("job cancelled"), 1000);
try {
await fetch("https://httpbin.org/delay/5", {
signal: controller.signal,
});
} catch (err) {
console.log(err); // job cancelled
}
Combining a timeout with a manual stop:
const stop = new AbortController();
const signal = AbortSignal.any([
AbortSignal.timeout(5000),
stop.signal,
]);
try {
await fetch("https://httpbin.org/delay/5", { signal });
} catch (err) {
console.log(signal.reason);
}
Checking before doing work:
function save(record, signal) {
signal.throwIfAborted();
return fs.writeFile("/record.json", JSON.stringify(record));
}