Understanding the return value of the yield keyword in the ES6 syntax

Source: Internet
Author: User

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
    1. Yield keyword
    2. Generator function Syntax (function*)
    3. asynchronous operations and Async functions

Understanding the return value of the yield keyword in the ES6 syntax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.