Collapse duplicate in-flight requests
Independent components requesting the same resource on mount is normal, and firing five identical requests is wasteful. The fix is to remember the promise that is already in flight and hand the same one to every later caller until it settles.
Implement singleFlight(fn). It returns a wrapped function whose **first argument is the key**. When called with a key that has a call in flight, return the exact same promise object without calling fn again. Otherwise call fn with all the arguments it was given and remember the resulting promise under that key. Once that promise settles — whether it fulfils or rejects — remove the entry, so the next call starts fresh work. A rejection is shared by every caller waiting on it.
What it has to do
- Return the identical promise object for concurrent calls with the same key.
- Call
fnonly once per set of concurrent calls with the same key. - Treat different keys as independent.
- Drop the cached promise once it settles, so a later call re-runs
fn. - Share rejections with every concurrent caller.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.