import { timeout } from "@daiso-tech/core/async";
import { AsyncHooks, TimeSpan } from "@daiso-tech/core/utilities";
const abortController = new AbortController();
const promise = new AsyncHooks(async (url: string, signal?: AbortSignal): Promise<unknown> => {
const response = await fetch(url, {
signal
});
const json = await response.json();
if (!response.ok) {
throw json
}
return json;
}, timeout({
time: TimeSpan.fromSeconds(2),
// With the defined signalBinder the HTTP request will be arboted when timed out or when the inputed `AbortSignal` is called.
signalBinder: ([url, fetchSignal], timeoutSignal) => {
return [
url,
AbortSignal.any([
fetchSignal,
timeoutSignal
].filter(signal => signal !== undefined))
] as const;
}
}))
.invoke("ENDPOINT", abortController.signal);
abortController.abort();
// An error will be thrown.
await promise;
The
timeout
middleware automatically cancels functions after a specified time period, throwing an error when aborted. Note the original function continues executing (even if the promise fails), you'll need to provide a settings.signalBinder to forward theAbortSignal
.IMPORT_PATH:
"@daiso-tech/core/async"