Home>Article>Web Front-end> What does yield mean in es6?
In ES6, yield is a keyword used by the generator to internally pause its own operation; yield is followed by a generator function or other iterable object, and the return value of the yield expression is the iterable object behind it. The return value when the iteration is completed, the syntax is "function*gen(){yield expression}".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
yield is a keyword used by Generator in ES6 to internally pause its own operation.
Please note the word "internal". The generator function cannot be paused by external logic, but can only be paused by itself through yield.
The yield keyword can be followed by a variable or used alone. If yield is followed by a variable (we can call it a yield expression), when the generator function resumes running after being paused, the parameters passed in will participate in subsequent logical operations as the value of the overall yield expression;
When Variables are not followed after yield. Yield used alone is only used as a pause generator function. After the generator resumes operation, the parameters passed in are used as the value of yield to participate in subsequent operations.
Example
Step 1, construct a generator function.
function* numbers () { yield 1; yield 2; return 'numbers'; }
Step 2, make a proxy outside the above generator function.
function* delegate () { var str = yield* numbers(); console.log(str); yield 3; return 'delegate'; }
Step 3, construct the iterator.
var iterator = delegate();
Step 4, output the iteration results.
/** * 第一次输出结果 * { value: 1, done: false } */ console.log(iterator.next()) // 第一次输出 /** * 第二次输出结果 * { value: 2, done: false } */ console.log(iterator.next()) // 第二次输出 /** * 第三次输出结果 * numbers * { value: 3, done: false } */ console.log(iterator.next()) // 第三次输出 /** * 第四次输出结果 * { value: 'delegate', done: true } */ console.log(iterator.next()) // 第四次输出
Output result description
When outputting for the third time, two lines of content are output. The content of the first line is the output of console.log(str) in the delegate function, and the value is the return value of the numbers function.
When outputting for the fourth time, a line of content is output, in which the value value is the return value of the delegate function. At this point, the done property is true.
【Related recommendations:javascript video tutorial,web front-end】
The above is the detailed content of What does yield mean in es6?. For more information, please follow other related articles on the PHP Chinese website!