javascript 29 lines · 6 steps

Deduplicating in-flight requests in JavaScript

A small wrapper that collapses concurrent identical requests into a single shared promise.

Explained by highlit
1class RequestDeduplicator {
2 constructor(fetcher) {
3 this.fetcher = fetcher;
4 this.inFlight = new Map();
5 }
6 
7 async fetch(key, ...args) {
8 const existing = this.inFlight.get(key);
9 if (existing) return existing;
10 
11 const promise = this.fetcher(...args).finally(() => {
12 this.inFlight.delete(key);
13 });
14 
15 this.inFlight.set(key, promise);
16 return promise;
17 }
18}
19 
20const userLoader = new RequestDeduplicator((id) =>
21 fetch(`/api/users/${id}`).then((res) => {
22 if (!res.ok) throw new Error(`Failed to load user ${id}: ${res.status}`);
23 return res.json();
24 })
25);
26 
27export function loadUser(id) {
28 return userLoader.fetch(String(id), id);
29}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing a promise (not its result) lets many callers await one shared operation.
  2. 2Cleaning up in finally ensures both success and failure free the slot for future retries.
  3. 3A stable key is what defines whether two requests count as identical.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deduplicating in-flight requests in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code