This is the third day of my participation in the August More Text Challenge

What is a generator

Generators are a special function new in ES6 that returns a generator object that implements the Iterable interface and can therefore be used on any Iterable. The unique thing about generators is that they support yield, and yield can suspend the execution of generator functions. You can also use the next() method to take input and produce output, and you can serialize the iterable that follows the keyword with an asterisk (*) to a series of values.

How to define a generator

A function name preceded by an * indicates that it is a generator, and generators can be defined as long as functions can be defined

      // Generator function declaration
       function* generatorFn() {}
       // Generator function expression
       let generatorFn = function* () {}
       // a generator function that acts as an object literal method
       let foo = {
           * generatorFn(){}}// a generator function that acts as a class instance method
       class Foo {*generatorFn(){}}// a generator function as a static method of the class
       class Bar {
           static * generatorFn(){}}Copy the code

Note: Arrow functions cannot be used to define generators

The generator starts in suspended state (suspended) and implements the Iterator interface. It can also call the next() method, which causes the generator to start or resume execution

        function * generatorFn(){};
        const f = generatorFn();
        console.log(f,f.next());
        //generatorFn {<closed>} Window {value: undefined, done: true}
Copy the code

Use yield to interrupt execution

The generator executes normally until the yield keyword is encountered, upon which execution stops, the scoped state of the function is preserved, and if stopped, the next() method is called to resume execution

        function * generatorFn(){
            yield;
        };
        const f = generatorFn();
        console.log(f.next()); //{value: undefined, done: false}
        console.log(f.next()); //{value: undefined, done: true}
Copy the code

The yield value appears in the next() method. Generator functions exiting with yield will be in the done: false state, and generators exiting with retutn will be in the done: true state

        function * generatorFn(){
             yield 'jackson';
            return 'bear';
        };
        const f = generatorFn();
        console.log(f.next()); //{value: "jackson", done: false}
        console.log(f.next()); //{value: "bear", done: true}
Copy the code

The yield keyword has a low priority, and almost all expressions after yield are evaluated first, except for the spread(expansion) operator and comma operators.

Generators can be used as default iterators

Generators are particularly suitable as default iterators because generator objects implement the Iterable interface, and because both generators and default iterators can be called to produce iterators

       class Foo {
            constructor() {
                    this.values = ['jackson'.'bear']; } * [Symbol.iterator]() {
                    yield* this.values; }}const f = new Foo();
        for (const x of f) {
            console.log(x);
        }
        // jackson 
        // bear
Copy the code

Premature termination generator

  1. return()

The return() method forces the generator into a shutdown state. The value supplied to the return() method is the value of the terminator object

Unlike iterators, all generator objects have a return() method that, once entered into a closed state, cannot be recovered. A subsequent call to next() displays the done: true state, and any return value provided is not stored or propagated:

  1. throw()

The throw() method injects a supplied error into the generator object when paused. If the error is not handled, the generator is shut down

Note that if the generator object has not yet started executing, the error thrown by the call to throw() will not be caught inside the function, since this is equivalent to throwing an error outside the function block