🛑 AbortController: Canceling Async Operations in JavaScript
Category: js / general-concepts
Difficulty: medium
AbortController is a built-in Web API that allows you to cancel asynchronous operations, especially ones that support an AbortSignal, like fetch, streams, or custom async tasks. 💡 Core Concepts AbortController Creates a controller with a .signal object. You call .abort() to cancel the operation. AbortSignal Passed to the async operation. Has .aborted boolean flag and emits an abort event. 🧪 Example: Cancel fetch [code example] 📦 Common Use Cases How AbortControllerHelps ✅ Native support Custom async tasks ✅ Combine with timeouts or control logic React effects 🧠 Example in Custom Code Create a wait(ms) function that supports cancellation via AbortController. [code example] Here’s a precise, fetch-cancelable promise implementation using AbortController : ✅ Cancelable Fetch with AbortController [code example] 🧪 Example: [code example] ✅ Behavior: Uses AbortController to terminate the underlying fetch request. If canceled, fetch rejects with AbortError. Unlike makeCancelable, this actually stops the request . ⚠️ Works With: fetch Some APIs like ReadableStream, Request, WebSocket (in newer specs) Let me know if you want a generic wrapper that adds cancelation to any* async operation (not just fetch). <!-- quiz-start --> Q1: What error name is thrown when a fetch request is aborted? [ ] CancelError [x] AbortError [ ] TimeoutError [ ] RequestError Q2: Which property of AbortController do you pass to fetch()? [ ] controller.abort [ ] controller.cancel [x] controller.signal [ ] controller.token Q3: What does signal.aborted return after calling abort()? [x] true [ ] false [ ] undefined [ ] "aborted" <!-- quiz-end -->...