timeout-fetch
Version:
Creates an instance of fetch that aborts after a certain time period.
42 lines (37 loc) • 1.1 kB
JavaScript
/**
* Timeout Fetch
* @module timeout-fetch
* @see {@link module:timeout-fetch.default}
*/
/**
* Error that is thrown when the timeout expires
*/
export class TimeoutError extends Error {}
export function* timeout(limit){
const ac = new AbortController();
const tid = setTimeout(ac.abort.bind(ac), limit);
const {signal} = ac;
try {
return yield signal;
} catch(e) {
if(signal.aborted) {
throw new TimeoutError(`The operation took longer than ${limit}ms and was aborted.`, { cause: e });
}
throw e;
} finally {
clearTimeout(tid);
}
}
/**
* Creates a fetch function that is aborted after a timeout period
* @param {number} count The timeout duration in miliseconds
* @param {function} fetch The fetch function to call, defaults to the global fetch
* @return {function} The created fetch function. Has the same signature as the passed param.
*/
export default function TimeoutFetch(count, fetch = globalThis.fetch) {
return async (request, options = {}) => {
for(const signal of timeout(count)) {
return await fetch(request, { ...options, signal });
}
};
}