abort-signal-polyfill
v1.0.0
Published
A lightweight polyfill for AbortSignal.any, AbortSignal.timeout, and AbortSignal.abort methods
Maintainers
Readme
abort-signal-polyfill
A lightweight polyfill for AbortSignal.any, AbortSignal.timeout, and AbortSignal.abort methods.
Features
AbortSignal.any(signals: AbortSignal[]): Creates an AbortSignal that will be aborted when any of the given signals is abortedAbortSignal.timeout(timeoutMs: number): Creates an AbortSignal that will be aborted after the specified timeoutAbortSignal.abort(reason?: any): Creates an AbortSignal that is already aborted with an optional reason
Installation
npm install abort-signal-polyfillUsage
import {
installAbortSignalPolyfill,
uninstallAbortSignalPolyfill,
} from 'abort-signal-polyfill';
// Install the polyfill
installAbortSignalPolyfill();
const timeoutSignal = AbortSignal.timeout(5000); // 5 second timeout
const controller = new AbortController();
// Combine signals - will abort if either timeout occurs or controller aborts
const signal = AbortSignal.any([timeoutSignal, controller.signal]);
try {
const response = await fetch(url, { signal });
const data = await response.json();
// Handle successful response
} catch (err) {
if (err.name === 'TimeoutError') {
// Handle timeout case
console.error('The request timed out');
} else {
// Handle other errors
console.error('Request failed:', err);
}
}
// Uninstall polyfills if needed
uninstallAbortSignalPolyfill();TypeScript Support
import type { AbortSignalPolyfill } from 'abort-signal-polyfill';
// For older TypeScript versions that may not have proper types for AbortSignal
(AbortSignal as AbortSignalPolyfill).timeout(2000);Browser Support
This polyfill works in all modern browsers that support AbortController and AbortSignal. For older browsers, you'll need to include a polyfill for AbortController first.
License
MIT
