Make a summary every day, persistence is victory!

/** @date 2021-06-11 @description ES6 Generator */Copy the code

One (sequence)

ES6’s Generator functions are an asynchronous programming solution.

Execution of a Generator function does not execute the code inside the function. Instead, it returns an traverser object. This means that a Generator function can be considered a traverser Generator, and the yield keyword is used internally to define different states. Several different states are managed internally.

Generator functions return a traverser object, so you need to call the next method to proceed, and the yield keyword is used to pause code. After each next call, the yield keyword is paused until the next call.

Inserting * between the function keyword and the function name indicates that the function is a Generator, and the yield keyword is placed inside the function to indicate a pause flag.

Ii (Use)

function *foo() {
    console.log(1);
    yield 'first';
    console.log(2);
    yield 'sec' + 'ond';
    console.log(3);
    return 'third';
    console.log(4);
    yield 'fourth';
}

const f = foo();
f.next(); // 1 {value: "first", done: false}
f.next(); // 2 {value: "second", done: false}
f.next(); // 3 {value: "third", done: true}
f.next(); // {value: undefined, done: true}
Copy the code

As you can see from the code and output above, executing a Generator function does not execute immediately, but waits for the next method to be called, and then executes the code between the first line of the function and the first yield keyword. The yield expression is executed when the corresponding next method is called. If the return keyword is the same as a normal function, it returns the value of return, and the following code does not continue to execute.

Iii (Application)

  1. You can useGeneratorLet’s do a functionDelay theFunction, which is not needed at this timeyieldKey words;
function * bar() { console.log('call bar! ') } bar = bar(); // bar {<suspended>} setTimeout(() => { bar.next(); // 'call bar! '}, 1000)Copy the code
  1. forObjectaddIteratorInterface;
const obj = {a: 1, b: 2};

obj[Symbol["iterator"]] = function *() {
    const self = this;
    const keys = Object.keys(self);
    
    for(let i = 0; i < keys.length; i++) {
        yield self[keys[i]]
    }
}

for(item of obj) {
    console.log(item); // 1 2
}
Copy the code