javascript 37 lines · 8 steps

Cancelling stale requests in a search client

A closure tracks the in-flight request so each new search aborts the previous one before firing.

Explained by highlit
1export function createSearchClient(baseUrl) {
2 let inFlight = null;
3 
4 async function search(query, { signal } = {}) {
5 if (inFlight) {
6 inFlight.abort();
7 }
8 
9 const controller = new AbortController();
10 inFlight = controller;
11 
12 if (signal) {
13 signal.addEventListener('abort', () => controller.abort(), { once: true });
14 }
15 
16 const url = `${baseUrl}/search?q=${encodeURIComponent(query)}`;
17 
18 try {
19 const response = await fetch(url, { signal: controller.signal });
20 if (!response.ok) {
21 throw new Error(`Search failed: ${response.status}`);
22 }
23 return await response.json();
24 } catch (err) {
25 if (err.name === 'AbortError') {
26 return null;
27 }
28 throw err;
29 } finally {
30 if (inFlight === controller) {
31 inFlight = null;
32 }
33 }
34 }
35 
36 return { search };
37}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Keeping a reference to the current request lets you cancel it the moment a newer one starts.
  2. 2Chaining an external signal to an internal controller lets callers cancel while the client still manages its own state.
  3. 3Treating AbortError as a non-error keeps intentional cancellations from crashing the caller.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Cancelling stale requests in a search client — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code