Implement dedupeRequests(fetcher). fetcher(key) starts some async work and returns a promise. Return a function get(key) that avoids duplicate work. A request is in flight while its promise has not settled yet.
- If a request for
keyis still in flight, return that same promise. Don't callfetcheragain. - Otherwise call
fetcher(key), remember its promise as in flight, and return it. - Once the promise settles (resolves or rejects), forget it. The next
get(key)callsfetcheragain. - Different keys never share a request.
- Forgetting a rejected request must not cause an extra unhandled rejection. An unhandled rejection is a rejected promise that no code catches.
Input: const get = dedupeRequests(fetchUser);
const a = get('u1'); const b = get('u1');
Output: fetchUser called once; a === b
Input: await get('u1'); get('u1');
Output: fetchUser called a second timeThe first request had settled, so nothing was in flight.