Chapter 12: Generators, advanced iteration
12.1 Generators
Generators can return (“yield”) multiple values, one after another, on-demand.
When the next()
is called, it runs the execution until the nearest yield <value>
statement.
The result (object):
value
: the yielded value.done
:true
if the function code has finished, otherwisefalse
.
Generators are iterable
We can loop over the generator using for..of
. However, it ignores the last value, when done: true
.
To fix that, we must return them with yield
.
Using generators for iterables
Generators may generate values forever.
Generator composition
There’s a special yield*
syntax to “embed” (compose) one generator into another.
“yield” is a two-way street
yield
not only returns the result to the outside, but also can pass the value inside the generator.
generator.throw
12.2 Async iterators and generators
Async iterators
Use
Symbol.asyncIterator
next()
should return a promiseUse
for await (let item of iterable)
loop to iterate over the objectThe spread syntax
...
doesn’t work asynchronously.
Async generators
Last updated