Module 41 // Core JavaScript

Generators & Async Iteration

Module Objective

yield, delegation, async generators, for await...of

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Infinite ID Generator
function* idMaker() {
  let id = 1;
  while (true) {
    yield id++;
  }
}

const ids = idMaker();
console.log(ids.next().value); // 1
console.log(ids.next().value); // 2
💡 Generators can contain infinite loops without crashing! They simply pause at the `yield` statement and wait for the next `.next()` call.
// Example 2
// 2. Two-way Communication
function* conversation() {
  const answer = yield "What is your name?";
  console.log("Hello, " + answer);
}

const chat = conversation();
console.log(chat.next().value); // "What is your name?"
chat.next("Subhajit");          // "Hello, Subhajit"
💡 Generators aren't just for outputs. You can pass a value back into the generator via `.next(value)`, which becomes the result of the `yield` expression inside the function.
// Example 3
// 3. Async Iteration (ES2018)
async function* fetchStream(urls) {
  for (const url of urls) {
    const res = await fetch(url);
    yield res.json();
  }
}

// Consumed with 'for await...of'
💡 Async Generators combine the power of Async/Await with Generators, allowing you to stream asynchronous results one-by-one.

Engine & Memory Architecture

The Suspended State

1. Context Retention:

  • Unlike regular functions, a Generator's Execution Context is not destroyed when it returns or yields.
  • It is moved from the Stack to the Heap, preserving the values of all local variables and the Instruction Pointer.

2. Resumption:

  • Calling .next() moves the context back to the Stack.
  • The CPU resumes execution from exactly where the last yield happened.

3. State Management:

  • Generators are essentially a very efficient way to build a Closure that also remembers "where" it stopped in the code.
  • Performance: This state management is handled natively by the engine, making it faster than many manual state machine implementations.