import { AsyncHooks } from "@daiso-tech/core/utilities";
const abortController = new AbortController();
// You can abort the function based on by your on criteria
abortController.abort("Aborted") // Remove this code if you want the function to aborted after 2 seconds by the middleware.
const data = await new AsyncHooks(async (url: string, signal?: AbortSignal): Promise<unknown> => {
const response = await fetch(url, { signal });
return await response.json();
}, [
(args, next, { abort, signal }) => {
// We abort the function when it execdes 2 seconds.
const id = setTimeout(() => abort("Timed out"), 2000);
// We remove the timeout if function is aborted before it execdes 2 seconds.
signal.addEventListener("abort", () => clearTimeout(id), { once: true });
return next(...args);
}
], {
signalBinder: {
getSignal: (args) => args[1],
forwardSignal: (args, signal) => {
args[1] = signal;
}
}
})
.invoke("url", abortController.signal);
console.log("DATA:", data)
With
AbortSignalBinder
, you can bind an AbortSignal |AbortSignal
to the middleware, enabling two-way abortion control. This means the middleware can abort the function, or the function can abort the middleware if the input function supports an AbortSignal |AbortSignal
.IMPORT_PATH:
"@daiso-tech/core/utilities"