Sporalize-api / src /single-flight.ts
Shoraky's picture
Improve backend request performance
82b44e7
Raw History Blame Contribute Delete
534 Bytes
/** 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;
};
}