Package Exports
- abortcontroller-deadline
- abortcontroller-deadline/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (abortcontroller-deadline) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Create an AbortController
which aborts after a set number of milliseconds (a deadline)
Works with browsers, NodeJS (16+), and spec-compliant polyfills.
Usage
Basic
import { createDeadline } from "abortcontroller-deadline";
// create an AbortController which aborts after 500 ms
const controller = createDeadline(500);
// use the controller! in this case, it ensures the fetch takes no longer than 500ms
try {
const response = await fetch("https://example.com", {
signal: controller.signal,
});
const data = await response.json();
} catch (error) {
if (error instanceof fetch.AbortError) {
console.log("Deadline exceeded");
}
}
Connecting existing signals
You can chain the output of other AbortSignals into the deadline: if any of the signals aborts before the deadline, the deadline controller will be aborted too:
const parentController = new AbortController();
const anotherController = new AbortController();
// if either parentController or anotherController abort, deadlineController
// will also abort, even if 500ms haven't passed
const deadlineController = createDeadline(
500,
parentController.signal,
anotherController.signal
);
Cleaning up timeouts / deadlines
Internally, the deadline is triggered by a timeout (from setTimeout()
). While not required, it is a good practice to clean up any unused timeouts.
createDeadline()
manages this by adding a clearDeadline()
to any returned controller:
import { createDeadline } from "abortcontroller-deadline";
const controller = createDeadline(500);
try {
const response = await fetch("https://example.com", {
signal: controller.signal,
});
/* ... */
} catch (error) {
/* ... */
} finally {
// clean up; this works whether or not the deadline occured
controller.clearDeadline();
}