liveBook · Manning

Finite-state machine

As explained in Secrets of the JavaScript Ninja, Second Edition

A model of a system as a set of states and transitions between those states.

A generator behaves like a small state machine: calls to its iterator’s next() method advance execution, while yield pauses it until the next request. section 6.2.4

A generator moves through four states:

  • Suspended start: created, but its code has not run. section 6.2.4
  • Executing: runs from the beginning or resumes where it paused. section 6.2.4
  • Suspended yield: produces a value and waits for another request. section 6.2.4
  • Completed: reaches return or runs out of code. section 6.2.4

A two-step generator

NinjaGenerator("skulk") first yields “Hattori skulk”; its next request reaches return and completes the generator with “Yoshi skulk.” section 6.2.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines four generator states and their transitions, then turns toward execution contexts.
Examples
Uses a generator that yields “Hattori skulk” and returns “Yoshi skulk.”
What it assumes
Assumes familiarity with generator calls, iterators, next(), yield, and return.
What you can do after
Understand how iterator requests advance a generator through its lifecycle.
How it connects
Connects generators with iterators, yield, and execution contexts.

Also explained in

Compare how 9 books explain finite-state machine →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.