ES6 Generator
Definition
ES6 provides an asynchronous programming solution.
There are multiple perspectives:
- Grammatically, it can be understood as a state machine that encapsulates multiple internal states.
- Calling a
Generatorfunction returns an iterator object, which is an implementation of theIteratorinterface. Thus,Generatorfunctions are not only state machines but also generator object creators. - Formally, a
Generatorfunction is a regular function (cannot be used as a constructor), but has two characteristics: - The
functionkeyword is followed by the function name with a star; - The function body uses
yieldexpressions to define different internal states (yieldmeans "producing" in English). next(): Moves the pointer to the next state and returns an object with two properties:valueanddone. Thevalueproperty represents the return value of the currentyieldexpression, and thedoneproperty is a boolean indicating whether there are moreyieldstatements in the generator function, i.e., whether the generator function has been executed to completion.throw(): Throws an error outside the function body and catches it within theGeneratorfunction.return(): Returns a specified value and terminates the traversal of theGeneratorfunction.
Calling and Execution
The calling method of Generator functions is the same as regular functions. However, when calling a Generator function, it does not execute and returns a pointer object to the internal state, i.e., an iterator object (not this), which cannot access attributes defined in the Generator function.
The next step is to call the next method of the iterator object to move the pointer to the next state. In other words, each call to next moves the internal pointer from the beginning of the function or the last stopped position, until the next yield expression (or return statement) is encountered. In essence, Generator functions are segmented, with yield expressions acting as markers for pausing execution and the next method allowing execution to be resumed.
yield Expression
The yield expression is a pause marker for Generator functions. When encountering a yield expression, execution is paused, and the value of the expression immediately following the yield is assigned as the value property of the returned object.
The yield expression itself does not return a value, or it always returns undefined. The next method can take a parameter, which is treated as the return value of the previous yield expression.
Methods
Common characteristics: Allows the Generator function to resume execution and replaces yield expressions with different statements.
Example
function* f() {
for(var i = 0; true; i++) {
var reset = yield i;
if(reset) { i = -1; }
}
}
var g = f();
g.next() // { value: 0, done: false }
g.next() // { value: 1, done: false }
g.next(true) // { value: 0, done: false }
