Generators
The ES2015 specification introduces another mechanism that, besides other things, can be used to simplify the asynchronous control flow of our Node.js applications. We are talking about generators, also known as semi-coroutines. They are a generalization of subroutines, where there can be different entry points. In a normal function, in fact, we can have only one entry point, which corresponds to the invocation of the function itself. A generator is similar to a function, but in addition, it can be suspended (using the yield
statement) and then resumed at a later time. Generators are particularly useful when implementing iterators, and this should ring a bell, as we already discussed how iterators can be used to implement important asynchronous control flow patterns such as sequential and limited parallel execution.
The basics of generators
Before we explore the use of generators for asynchronous control flow, it's important we learn some basic concepts. Let's start from...