CodePark/ problems / Share in-flight requests
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Async control flow

Share in-flight requests

mediumabout 20 minutes in an interview

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 key is still in flight, return that same promise. Don't call fetcher again.
  • 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) calls fetcher again.
  • 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.