A lightweight polyfill for AbortSignal.any
, AbortSignal.timeout
, and AbortSignal.abort
methods.
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
npm install abort-signal-polyfill
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();
import type { AbortSignalPolyfill } from 'abort-signal-polyfill';
// For older TypeScript versions that may not have proper types for AbortSignal
(AbortSignal as AbortSignalPolyfill).timeout(2000);
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.
MIT