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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Keeping a reference to the current request lets you cancel it the moment a newer one starts.
- 2Chaining an external signal to an internal controller lets callers cancel while the client still manages its own state.
- 3Treating AbortError as a non-error keeps intentional cancellations from crashing the caller.
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
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 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/cancelling-stale-requests-in-a-search-client-explained-javascript-980c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.