Generators
Generators
They make possible to pause a function execution, allowing the use of loop event cooperatively.
Used in Iterators.
function* forever() {
...
}
const foreverGenerator = forever();They use the next method to iterate over the available values during the function execution.
They return a
{ value: ..., done: ... }, following theIterableprotocol.
// This executes the function
foreverGererator.next()When a yield is found, the function execution is paused until the next is invoked again.
yieldcan accept a parameter that will be thevalueinside thenextiterable return.yield parameter.
function* forever() {
let i = 1;
while(true) {
...
yield i++;
}
}
const foreverGenerator = forever();
foreverGenerator.next(); // -> { value: 1, done: false }
foreverGenerator.next(); // -> { value: 2, done: false }
foreverGenerator.next(); // -> { value: 3, done: false }
foreverGenerator.next(); // -> { value: 4, done: false }yieldalso returns some value that can be passed fromnext(value).
return method closes this generator, and allows you to also return a specific value.
The throw method throws an exception inside the generator, breaking the execution if the exception is not treated.
If error is handled with
try/catchthe execution may continue withnextcalls.
Creating an Iterator with Generator
Generator can also be used to syncronize async calls similar to async/await.
Last updated