The syntax for the generator function is added in ES6, and this article explains the return value of the yield keyword within the generator function.
Describe
According to the syntax specification, the yield keyword is used to pause and resume execution of a generator function. The expression to the right of the yield keyword executes when the next () method of the generator is called externally.
The execution result is converted to an object (containing two attributes, value and done) as the return value of the next () method.
For the var foo = yield expression statement, the value of the variable foo on the left side of the yield is obtained at the next call to the next () method, and equals the parameter of the next () method at the time of the call Number .
Example
First, construct a generator function.
function* numbers () { console.log (' function start. ') ); var v1 = yield 0; Console.log (' v1 = ' + v1); var v2 = yield 1; Console.log (' v2 = ' + v2); return 5;} var nums = numbers ();
Call the generator function below.
// the 1th call to next, the value of V1 has not yet returned.
The program output is as follows.
function start. {value:0, Done:false}
Next, the second call is executed.
// the 2nd call to Next, the next parameter, is returned to V1 as the last yield value.
At this point the program output is as follows.
V1 = 3{value:1, done:false}
Finally, the third call is executed.
// The 3rd call to Next, when done evaluates to True, returns the value of return directly.
The program finishes execution and the output is as follows.
V2 = 4{Value:5, done:true}
Extended Reading
- Yield keyword
- Generator function Syntax (function*)
- asynchronous operations and Async functions
Understanding the return value of the yield keyword in the ES6 syntax