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 the Iterable protocol.

// This executes the function
foreverGererator.next()

When a yield is found, the function execution is paused until the next is invoked again.

  • yield can accept a parameter that will be the value inside the next iterable 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 }
  • yield also returns some value that can be passed from next(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/catch the execution may continue with next calls.

Creating an Iterator with Generator

Generator can also be used to syncronize async calls similar to async/await.

Last updated