How to follow async control flow in JavaScript code
Promises, async/await, callbacks, Promise.all, unawaited calls and the event loop: how to work out what actually runs when in asynchronous JavaScript.
In synchronous code, execution order matches reading order. In asynchronous JavaScript, it often doesn't. Code later in a function can run before code earlier in it, two operations can overlap, and a forgotten await can make a function return before its work is done. Reading async code well means tracking what runs when.
Know the basic rules
awaitpauses the current function until the promise settles; other code can run meanwhile.- A promise that isn't awaited runs in the background; its errors won't reach the caller's
try/catch. .thencallbacks run later, after the current synchronous code finishes.- Callbacks passed to timers, events and older APIs run whenever their trigger happens.
Spot sequential versus parallel
const user = await getUser(id);
const orders = await getOrders(id);These run one after the other. This version runs them at the same time:
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);When reading performance-sensitive code, mark which awaits are sequential and whether they need to be.
Know the Promise combinators
| Combinator | Behaviour |
|---|---|
Promise.all | Waits for all; rejects as soon as one rejects |
Promise.allSettled | Waits for all; never rejects; reports each result |
Promise.race | Settles with the first to settle |
Promise.any | Resolves with the first to fulfil; rejects only if all reject |
The choice changes error behaviour, so read it carefully.
Hunt for unawaited promises
Calls like sendEmail(user) without await, return or .catch run in the background. Sometimes that's intended ("fire and forget"). Often it's a bug: errors disappear, and in serverless environments the work may be cut off when the response is sent. ESLint's no-floating-promises rule (from typescript-eslint) finds these automatically.
Watch async inside loops
for...ofwithawaitinside runs iterations one at a time.array.forEach(async ...)starts all iterations and doesn't wait for any of them; the function continues immediately.await Promise.all(array.map(async ...))runs all in parallel and waits.
forEach with an async callback is one of the most common async bugs.
Follow callbacks and events
For callback- or event-based code, number each callback in the order it will run, not the order it appears. Event handlers registered with on run every time the event fires, not once.
Use the debugger's async stack
Modern debuggers show async stack frames, so you can see which code scheduled the current callback. It's the quickest way to answer "how did execution get here?" in async code.
Ask about timing
Ask RepoGrasp "which calls in handleCheckout run in parallel, which run in sequence, and are any promises not awaited?" It reads the function and its callees and cites each call. Timing bugs are subtle, so confirm with a test or logs.