Single Flight Dedupe Concurrent Calls

Deduplicate concurrent identical calls to an async function so only one execution runs and all callers share its result.

JavascriptResilience

Code

javascriptsnippet
1 line
export function singleFlight(fn){const inFlight=new Map();async function d(...a){const key=JSON.stringify(a);if(inFlight.has(key))return inFlight.get(key);const p=fn.apply(this,a).finally(()=>inFlight.delete(key));inFlight.set(key,p);return p;}d.inFlight=inFlight;return d;}

What the code does

Single Flight Dedupe Concurrent Calls keeps everything in the functions singleFlight and d.

Await points sequence the asynchronous work; a rejection lands at the awaiting line.

Using it in your own code

The main signature reads export function singleFlight(fn)

singleFlight is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `singleFlight`, `d` at load time.