timeout.ts
This file
Path
source/utils/timeout.ts
32 lines · 684 bytes · TypeScript
Last changed by
Fix support with environments that add support for custom `fetch` options (#536)Kelvin Del Montebefore adoptione93bc6d
History of this fileTake it
123456789101112131415161718192021222324252627282930313233import {TimeoutError} from '../errors/TimeoutError.js';
export type TimeoutOptions = { timeout: number; fetch: typeof fetch;};
// `Promise.race()` workaround (#91)export default async function timeout( request: Request, init: RequestInit, abortController: AbortController | undefined, options: TimeoutOptions,): Promise<Response> { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { if (abortController) { abortController.abort(); }
reject(new TimeoutError(request)); }, options.timeout);
void options .fetch(request, init) .then(resolve) .catch(reject) .then(() => { clearTimeout(timeoutId); }); });}