async/await & Cancellation
Write asynchronous code that reads like ordinary statements, run independent work concurrently, and cancel requests that are no longer needed.
By the end, you’ll be able to…
- Write async functions and handle rejections with try/catch.
- Choose between sequential awaits and concurrent Promise.all work.
- Cancel in-flight work with AbortController and recognize unhandled rejections.
01async and await make promises readable
An async function always returns a promise. Inside it, await pauses that function until the awaited promise settles, then resumes with the fulfillment value or throws the rejection reason. It does not block the thread: other tasks continue while the function is suspended, which is why the event loop can still respond to clicks.
Use try/catch around the awaits you expect to fail. A return await inside a try block is meaningful when you want a rejection from the returned promise to be caught by that same try. Outside error handling, return promise and return await promise are nearly equivalent, but the explicit await makes the recovery path obvious.
02Sequential versus parallel awaits
Each await waits for the previous one. That is correct when the second request needs a value from the first, but wasteful when two requests are independent. Starting both promises first and awaiting Promise.all overlaps the waiting time instead of adding it.
A loop of awaits is sequential by design. If the iterations are independent, map them to promises and await the combined array. Limit concurrency when the list is large or the server is sensitive; firing a thousand requests at once can be slower and less polite than a small worker pool.
Promise.all is fail-fast: if one request rejects, the combined promise rejects even though the others keep running. When partial success is acceptable, use Promise.allSettled and render what arrived. When order matters, await each step in turn; when it does not, start everything first and await once.
03Cancel work with AbortController
AbortController owns a signal that you pass to cancellable APIs such as fetch. Calling controller.abort() marks the signal as aborted; the pending request rejects with an AbortError instead of continuing to consume bandwidth and memory. A controller can be reused only by creating a new one for each operation.
Cancellation is essential for search boxes, tab switches, and navigation. When a newer request supersedes an older one, abort the older controller before starting the new request. Always check the error name and return quietly for an abort; showing an error message for work the user intentionally replaced is misleading.
04Timeouts and unhandled rejections
Modern runtimes support AbortSignal.timeout(ms), which aborts automatically after a deadline. Combine it with fetch and translate the resulting TimeoutError into a message your interface can display. A timeout is not the same as a user cancellation, so distinguish the two in your error handling.
Every promise you start needs an owner. If an async event handler rejects and nothing catches it, the browser reports an unhandledrejection event and Node.js can terminate the process. A global listener is useful for logging, but it is a safety net, not a substitute for handling errors at the call site.
A timeout signal cancels the request, but it does not undo server-side work. Design endpoints to be idempotent where retries are possible, and show a retry action rather than silently repeating a mutation.
The ideas worth keeping.
- async functions return promises, and await pauses only the function rather than the thread.
- Await independent work through Promise.all to overlap waits; keep sequential awaits for dependent steps.
- Abort superseded requests with a fresh AbortController, and always handle the promise you start.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Load independent data concurrently
Write an async function that loads a user and a list of orders at the same time, then returns both. Include a comment explaining why the two await calls are not written one after the other.
Explore a worked solution
const loadUser = () => Promise.resolve({ id: 1, name: "Ada" });const loadOrders = () => Promise.resolve([{ id: 10 }, { id: 11 }]);async function loadDashboard() { // Both promises start before either is awaited, so the waits overlap. const [user, orders] = await Promise.all([loadUser(), loadOrders()]); return { user, orders };}loadDashboard().then(({ user, orders }) => { console.log(`${user.name} has ${orders.length} orders`);});Passing the promises directly to Promise.all starts both operations before awaiting. The function returns when both settle, and the two waits overlap instead of adding together. The output is Ada has 2 orders.
Exercise 2: Abort the previous request
Create a makeSearch function that keeps one active AbortController. Each call aborts the previous request before fetching, and ignores an AbortError instead of logging it.
Explore a worked solution
let activeController = null;async function makeSearch(term) { activeController?.abort(); activeController = new AbortController(); try { const response = await fetch(`/api/search?q=${encodeURIComponent(term)}`, { signal: activeController.signal, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { if (error.name === "AbortError") return null; throw error; }}Aborting the old controller rejects the old fetch with an AbortError, which the function converts to null. The new request has a fresh signal, so it is unaffected. Returning quietly prevents a stale search from showing an error.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Load independent data concurrently
Write an async function that loads a user and a list of orders at the same time, then returns both. Include a comment explaining why the two await calls are not written one after the other.
[Process exited with code 0 - No output]
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.