Spaces:
Running
Running
File size: 534 Bytes
82b44e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** Share only concurrent work. Completed values and failures are never cached. */
export function singleFlight<Key, Value>(load: (key: Key) => PromiseLike<Value>) {
const pending = new Map<Key, Promise<Value>>();
return (key: Key): Promise<Value> => {
const existing = pending.get(key);
if (existing) return existing;
const request = Promise.resolve().then(() => load(key)).finally(() => {
if (pending.get(key) === request) pending.delete(key);
});
pending.set(key, request);
return request;
};
}
|