mediumcodingjavascript~12 min
Deduplicate In-Flight Requests
Objective: Avoid duplicate network calls from components mounting at the same time.
Implement `dedupe(fn)`: while a call for a given key is still pending, other callers with the same key share the same promise. Once it settles, the next call starts a new request.
- The key is `JSON.stringify(args)`.
- Concurrent calls with the same key return the same promise and call fn once.
- After success or failure the entry is removed so later calls refetch.
- Different keys do not interfere.
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- How is this different from caching results?
- What does stale-while-revalidate add on top?
- How does cancelling one caller affect the shared request?