15 lines
503 B
TypeScript
15 lines
503 B
TypeScript
/**
|
|||
|
|
* Share one in-flight promise per key: callers that ask again while a request
|
||
|
|
* for the same key is still pending get that request instead of a new one.
|
||
|
|
*/
|
||
|
|
export function dedupeInFlight<T>(): (key: string, run: () => Promise<T>) => Promise<T> {
|
||
|
|
const pending = new Map<string, Promise<T>>();
|
||
|
|
return (key, run) => {
|
||
|
|
const existing = pending.get(key);
|
||
|
|
if (existing) return existing;
|
||
|
|
const p = run().finally(() => pending.delete(key));
|
||
|
|
pending.set(key, p);
|
||
|
|
return p;
|
||
|
|
};
|
||
|
|
}
|