Overview
- Debounces an async function.
- Cancels stale calls via AbortController.
- All callers resolve with the latest call’s result (coalesced resolution).
Implementation (TypeScript)
export type DebouncedAsync<TArgs extends unknown[], TResult> =
(...args: TArgs) => Promise<TResult>;
/**
* Debounce an async function. The wrapped function receives an AbortSignal as its first argument.
* - Stale scheduled or in-flight calls are aborted.
* - Every invocation resolves/rejects with the latest executed call's outcome.
*/
export function debounceAsync<TArgs extends unknown[], TResult>(
fn: (signal: AbortSignal, ...args: TArgs) => Promise<TResult>,
wait: number
): DebouncedAsync<TArgs, TResult> {
let timer: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | null = null;
let lastArgs: TArgs | null = null;
// All outstanding callers waiting for the "latest" result
let pending: Array<{ resolve: (v: TResult) => void; reject: (e: unknown) => void }> = [];
return (...args: TArgs): Promise<TResult> => {
lastArgs = args;
// Cancel any pending timer and in-flight work
if (timer) clearTimeout(timer);
if (controller) controller.abort();
const promise = new Promise<TResult>((resolve, reject) => {
pending.push({ resolve, reject });
});
controller = new AbortController();
timer = setTimeout(async () => {
const localController = controller!;
const callArgs = lastArgs as TArgs;
try {
const result = await fn(localController.signal, ...callArgs);
// If this call was aborted after completion, ignore its result
if (localController.signal.aborted) return;
const waiters = pending;
pending = [];
for (const { resolve } of waiters) resolve(result);
} catch (err) {
// Swallow abort errors; next (latest) call will settle all waiters
if (localController.signal.aborted) return;
const waiters = pending;
pending = [];
for (const { reject } of waiters) reject(err);
}
}, wait);
return promise;
};
}Usage Example
// Debounced search that aborts stale network requests.
// Note: fetch respects AbortSignal natively.
const search = debounceAsync(async (signal, query: string) => {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<{ items: string[] }>;
}, 300);
// Rapid calls: only the latest ("react") request runs to completion.
// All three promises resolve with the same final result.
const p1 = search("r");
const p2 = search("rea");
const p3 = search("react");
const result = await p1; // same as await p2 and await p3
console.log(result.items); // latest search results
