Generators
Generators¶
Also called function *, generators allow you to create functions whose execution can be paused and then later resumed maintaining the state between pause-resume transitions. The value returned from a generator is called an iterator and can be used to control this pause-resume transition.
Here is a simple example of a generator function that generates an infinite list of whole numbers.
1 2 3 4 5 6 | |
The yield contextual keyword is used to return control from a generator (effectively pausing function execution) along with an optional value (here current). You can get access to this value using the iterator's .next() member function, this is shown below:
1 2 3 4 5 6 7 8 9 10 11 | |
Now that you have seen function*, yield and .next() we can dig deeper.
Catching Errors¶
Any errors thrown (intentially using throw or unintentionally due to error) from the generator can be caught using try/catch just like normal function executions. This is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Controlling function execution externally¶
The iterator returned from the generator function can be used to control the state inside the generator function as well.
// TODO: example