In a time just before the rise of the Promises, they came and fell to oblivion in a blink. Sadly nobody uses them, including me, but generators are still in the game (or not). Maybe you remember this strange
yield expression or the tiny
* declaration to transform your dummy function into a beautiful generator.
So yes, you can use
async/await, almost any
Add a star (
*) to your function declaration, multiple returns (
yield) and voilà, you just have created a generator!
There are only three methods attached to the Generator's prototype :
.next(): return the next “yielded” value
.return(): return the given value and force the generator to end (kill switch)
.throw(): throw an error to the generator and finish it in a more errorish way
When to use it ?
Generators are very useful when you need a method that you can replay on demand with some kind of inner evolution. Something not as autonomous as a recursive method and not as dummy as a multi-parameters function. In summary, an iterator.
In the following example, we want to add a new item to our list when clicking on a button, but with a maximum of
10 items :
It illustrates how cool generator can be in that case. You can keep the iteration logic inside your method, no need to keep track of the current or last index in an external variable. Simple, clear, elegant, plus the useful
done value to check the progress.
async/await syntax :innocent: