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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing a promise (not its result) lets many callers await one shared operation.
- 2Cleaning up in finally ensures both success and failure free the slot for future retries.
- 3A stable key is what defines whether two requests count as identical.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/deduplicating-in-flight-requests-in-javascript-explained-javascript-6992/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.