Generators Pattern
Explore the Generators Pattern in Node.js to understand how generator functions serve as powerful iterators with multiple entry points. Learn to control asynchronous flow by pausing and resuming execution using yield and manage generator objects effectively within your applications.
The ES2015 specification introduced a syntax construct that’s closely related to iterators. We’re talking about generators, also known as semicoroutines. They’re a generalization of standard functions, in which there can be different entry points. In a standard function, we can have only one entry point, which corresponds to the invocation of the function itself, but a generator can be suspended (using the yield statement) and then resumed at a later time. Among other things, generators are very well suited to implement iterators, in fact, as we’ll see in a bit, the generator object returned by a generator function is indeed both an iterator and an iterable.
Generators in theory
To define a generator function, we need to use the function* declaration (the function keyword followed by an asterisk).
function * myGenerator () {// generator body}
Invoking a generator function won’t execute its body immediately. Rather, it’ll return a generator object, which, as we already mentioned, is both an iterator and an iterable. But it doesn’t end here; invoking next() on the generator object will start or resume the execution of the generator until the yield instruction is invoked or the generator returns (either implicitly or explicitly with a return instruction). Within the generator, using the keyword yield followed by a value x is equivalent to returning {done: false, value: x} from the iterator, while returning a value x is ...