Debugging Async Generators
In this lesson, you will learn how to use breakpoints and inspection tools to trace the internal state of asynchronous generators as they pause and resume during iteration.
When you work with async generators, the "magic" of yield and await can make it difficult to visualize where your data is actually hanging. Unlike a standard synchronous loop, an async generator suspends its execution context every time it hits an await or yield, making traditional console.log statements insufficient for tracking the flow of values.
Using Breakpoints effectively
To debug effectively, you should use the built-in debugger in VS Code or Chrome DevTools. When you place a breakpoint inside an async generator, the debugger tracks the Generator Object.
Consider this simple generator:
async function* streamNumbers() {
const data = [1, 2, 3];
for (const num of data) {
await new Promise(resolve => setTimeout(resolve, 100)); // The pause point
yield num;
}
}
When you hit a breakpoint on the yield line, look at the Call Stack and Scope panels:
- The Scope Panel: This is your best friend. Even though the function is suspended, the scope panel shows you the current value of
numand the state of your variables. - The "Step Into" (F11) vs. "Step Over" (F10): When you are at an
await, "Step Into" will often take you deep into the internal plumbing of the Promise implementation. Use "Step Over" to move to the next line within your generator instead. - Tracking the Iteration: Since an async generator is essentially a state machine, the debugger shows you which "state" it is in. You can observe the generator object’s
[[GeneratorState]]property, which will transition fromsuspendedYieldtorunningas you resume execution.
By inspecting the local variables at each breakpoint, you can verify if your stateful logic—such as a running total or an external stream buffer—is being updated correctly before the next yield pushes the value out to the consumer.
Key Takeaway: Use the debugger's Scope panel while stepping through your generator to inspect how local variables persist and change during each suspended state.