Chapter 12: Generators, advanced iteration

12.1 Generators

Generators can return (“yield”) multiple values, one after another, on-demand.

function* generateSequence() {
  yield 1;
  yield 2;
  return 3;
}

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, otherwise false.

let generator = generateSequence();

let one = generator.next();

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

  1. Use Symbol.asyncIterator

  2. next() should return a promise

  3. Use for await (let item of iterable) loop to iterate over the object

  4. The spread syntax ... doesn’t work asynchronously.

Async generators

Last updated