Es6 notes 6 ^_^ generator, es6 notes 6 generator

Source: Internet
Author: User

Es6 notes 6 ^_^ generator, es6 notes 6 generator
1. Introduction

The Generator function is a traversal of the internal state of a function (that is, the Generator function is a state machine ).
Formally, the Generator function is a common function, but has two features.
  • There is an asterisk * between the function command and the function name *;
  • The function body uses the yield statement to define each member of the traversal, that is, different internal states.
    function* helloWorldGenerator() {        yield 'hello';        yield 'world';        return 'ending';    }    let hw = helloWorldGenerator();   console.log(hw.next());// { value: 'hello', done: false }    console.log(hw.next());// { value: 'world', done: false }    console.log(hw.next());// { value: 'ending', done: true }    console.log(hw.next());// { value: undefined, done: true }
Summary:
  • Call the Generator function and return an Iterator object deployed to operate internal pointers.
  • In the future, each time the next method of the traversal object is called, an object with two attributes: value and done will be returned.
  • The value Attribute indicates the value of the current internal status, which is the value of the expression after the yield statement; the done attribute is a Boolean value that indicates whether the traversal is complete.
2. Parameters of the next Method
The yield statement itself does not return a value, or it always returns undefined. The next method can contain a parameter, which is treated as the return value of the previous yield statement.
    function* f() {        for(let i=0; true; i++) {            var reset = yield i;            if(reset) { i = -1; }        }    }    let g = f();    console.log(g.next()); // { value: 0, done: false }    console.log(g.next()); // { value: 1, done: false }    console.log(g.next(true));// { value: 0, done: false }
The code above first defines a Generator function f that can be run infinitely. If the next method does not have a parameter, the value of the variable reset is always undefined every time the yield statement is run.
When the next method includes a parameter true, the current variable reset is reset to this parameter (that is, true), so I will be equal to-1, the next cycle starts from-1.
3. for... of Loop
For... of loop can automatically traverse the Generator function, and you do not need to call the next method at this time.
function *foo() {    yield 1;    yield 2;    yield 3;    yield 4;    yield 5;    return 6;}for (let v of foo()) {    console.log(v);// 1 2 3 4 5}
The code above uses the for... of loop to display the values of five yield statements in turn.
Note:
Once the done attribute of the returned object of the next method is true,... the loop will be aborted and does not contain the returned object. Therefore, the return Statement of the code above returns 6, not included in the... of loop.
The following is an example of using the generator function and for... of loop to implement the Fibonacci series.
function* fibonacci() {    let [prev, curr] = [0, 1];    for (;;) {        [prev, curr] = [curr, prev + curr];        yield curr;    }}for (let n of fibonacci()) {    if (n > 1000) break;    console.log(n);}
The code above shows that the next method is not required when the for... of statement is used.
4. throw Method
The Generator function can also deploy error handling codes to capture the out-of-body errors thrown by the function.
Function * gen (x) {try {var y = yield x + 2;} catch (e) {console. log (e) ;}return y ;}let g = gen (1); g. next (); g. throw ('error error'); // Error
The last line of the code above, the Generator function in vitro, uses the throw method of the pointer object to throw the error, can be captured by the try... catch code block in the function body.
This means that the Code with errors is separated from the code with errors in processing time and space, which is undoubtedly important for asynchronous programming.
5. yield * Statement
If the yield command is followed by a traversal tool, you need to add an asterisk after the yield command to indicate that it returns a traversal tool. This is called the yield * Statement.
In fact, the yield keyword allows us to create an iterator for Traversing finite series sets in a more intuitive and convenient way, yield is used to segment the code of the generator function as an element of a finite sequence set (the element type is command + data, not just data ). Let's take a look at how the yield keyword slices the code!
Define generator Functions
Function * enumerable (msg) {document. write (msg) var msg1 = yield msg + 'after' document. write (msg1) var msg2 = yield msg1 + 'after' document. write (msg2 + 'over')} // The code above will be parsed into the following code: var enumerable = function (msg) {var state =-1 return {next: function (val) {switch (++ state) {case 0: document. write (msg + 'after') break case 1: var msg1 = val document. write (msg1 + 'after') break case 2: var msg2 = val document. write (msg2 + 'over') break }}}}
6. Generator function as Object Property
If the attribute of an object is a Generator function, it can be abbreviated to the following form.
Let obj1 = {* myGeneratorMethod () {}}; // In the code above, there is an asterisk in front of the myGeneratorMethod attribute, indicating that this attribute is a Generator function. // Its complete form is as follows, which is equivalent to the preceding method. Let obj2 = {myGeneratorMethod: function *(){}};

This article is to be continued ......

Related Article

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.