Generators are one of the most underused features in JavaScript. At Google, we use them for lazy evaluation, pagination, and complex async flows.
The Iterator Protocol
Any object with a next() method returning { value, done } is an iterator. Any object with [Symbol.iterator]() returning an iterator is iterable.
Generator Functions
Generators are functions that can pause and resume. The yield keyword pauses execution and returns a value.
Practical Use Cases
1. Lazy Pagination
2. Cancellable Async Flows
Unlike Promises, generators can be cancelled by simply not calling next() again. This is the foundation of libraries like Redux-Saga.
3. Tree Traversal
Generator + Async = Power
Async generators (async function*) combine the best of both worlds — lazy evaluation with async data sources. This is how Node.js streams work under the hood.