Async & Promisesmedium
Implement cancellable async flow with AbortController
Show how to make async requests cancellable using `AbortController`, and explain how to avoid race conditions in rapid user interactions.
Asked at Meta, TikTok, Stripe
Answer
// Interview explanation: // Promises are not cancellable by themselves. // Cancellation is usually modeled via AbortSignal passed to APIs (fetch, streams).
function createSearchClient(endpoint) { let controller = null
return async function search(query) { // cancel previous in-flight request if (controller) controller.abort() controller = new AbortController()
try {
const res = await fetch(
`${endpoint}?q=${encodeURIComponent(query)}`,
{ signal: controller.signal }
)
if (!res.ok) throw new Error('HTTP ' + res.status)
return await res.json()
} catch (err) {
if (err && err.name === 'AbortError') {
// expected cancellation path; do not show error toast
return null
}
throw err
}
} }
// Usage const search = createSearchClient('/api/search') // rapid typing: only latest request is allowed to complete search('rea') search('react') search('react hooks')