( fn: (key: string) => Promise<T>, )
| 4 | } |
| 5 | |
| 6 | export function createCoalescedAsyncRunner<T>( |
| 7 | fn: (key: string) => Promise<T>, |
| 8 | ): CoalescedAsyncRunner<T> { |
| 9 | const inFlight = new Map<string, Promise<T>>(); |
| 10 | const queued = new Set<string>(); |
| 11 | |
| 12 | function run(key: string): Promise<T> { |
| 13 | const existing = inFlight.get(key); |
| 14 | if (existing !== undefined) return existing; |
| 15 | |
| 16 | const promise = (async () => fn(key))().finally(() => { |
| 17 | inFlight.delete(key); |
| 18 | if (queued.delete(key)) { |
| 19 | void run(key); |
| 20 | } |
| 21 | }); |
| 22 | inFlight.set(key, promise); |
| 23 | return promise; |
| 24 | } |
| 25 | |
| 26 | function request(key: string): void { |
| 27 | if (inFlight.has(key)) { |
| 28 | queued.add(key); |
| 29 | return; |
| 30 | } |
| 31 | void run(key); |
| 32 | } |
| 33 | |
| 34 | return { run, request }; |
| 35 | } |
no outgoing calls
no test coverage detected