JavaScript Learning Notes (13)--Generator (generator)

Source: Internet
Author: User

In the study of Liaoche predecessors of the JavaScript tutorial, encountered some points needing attention, so as a study notes listed, remind yourself to notice!

If you have the need, welcome to visit the previous blog https://www.liaoxuefeng.com/ study.

The generator (generator) is the new data type introduced by the ES6 standard. A generator looks like a function, but can be returned multiple times.

Let's take a look at the concept of a function:

A function is a complete piece of code, calling a function is passing in a parameter, and then returning the result.

function foo (x) {    return x + x;} var // Call the Foo function

In the execution of the function, if no return statement is encountered, control cannot be returned to the called Code. ( if not at the end return of return undefined; the function, it is implied )

Generator definition
function* foo (x) {    + 1;     + 2;     return x + 3;}
The difference between generator and function

Generator is defined by function* (Note the extra * number) and, in addition to the return statement, can be returned multiple times with yield .

An example is easy to understand:

The famous Fibonacci sequence, which is preceded by 0, 1:

0 1 1 2 3 5 8 13 21 34 ...

To write a function that produces a Fibonacci sequence, you can write:

 function   FIB (max) { var   T, a  = 0, b  = 1     = [0, 1 while  (arr.length < Max) {[A, b] = [B, a + b];    Arr.push (b);  return   arr;}  //  test:  fib (5); //  [0, 1, 1, 2, 3]  fib (10); //  [0, 1, 1, 2, 3, 5, 8,, +]  

function can only be returned once, so one Array must be returned .

However, if you switch to generator, you can return one number at a time, returning multiple times . Rewrite with generator as follows:

' Use strict '
function* fib (max) {    var        T,        = 0,        = 1,        = 0;      while (N < max) {        yield A;         = [B, a + b];         ++;    }     return ;}

Call directly:

// fib {[[Generatorstatus]]: "Suspended", [[[Generatorreceiver]]: window}

We find that calling a generator directly is not the same as calling a function, and fib (5) simply creates a generator object and does not execute it.

There are two methods to call the Generator object:

One is to constantly invoke the next () method of the Generator object:

 var  f = fib (5 //  {value:0, done:false}  f.next (); //  {value:1, done:false}  f.next (); //  {value:1, done:false}  f.next (); //  {value:2, done:false}  f.next (); //  {value:3, done:false}  f.next (); //  {value:undefined, done:true}  

The Next () method executes the code of generator, and then, each time yield x is encountered, returns an object {value:x, done: true/false} , and then " Pause ". The value returned is the return value of yield , and done indicates whether the generator has been executed . If done is true , value is the return value of return.

When execution is true , the generator object is fully executed and no further calls to next () .

The second is to iterate the generator object directly with For......of , which does not need to be judged by ourselves:

for (Var x of fib (10)) {
Console.log (x); Output 0, 1, 1, 2, 3, ...
}

Generator advantages

1. It is because generator is able to return multiple times during execution, so it looks like a function that remembers the state of execution, and with this, you can write a generator to implement functions that need to be object-oriented.

For example, using an object to save the state, we usually use the object's properties to save. This is tedious:

varFIB ={A:0, B:1, N:0, Max:5, Next:function () {        varR= This. A, T= This. A + This. b;  This. A = This. b;  This. B =T; if( This. N < This. Max) {             This. N + +; returnR; } Else {            returnundefined; }    }};

Another big benefit of the 2.generator is that it turns the async callback code into a "synchronous" code.

Without generator, you need to write code like this when using Ajax:

Ajax (' Http://url-1 ', data1,function(err, result) {if(err) {returnhandle (ERR); } Ajax (' Http://url-2 ', data2,function(err, result) {if(err) {returnhandle (ERR); } Ajax (' Http://url-3 ', data3,function(err, result) {if(err) {returnhandle (ERR); }            returnsuccess (result);    }); });});

The more callbacks, the more ugly the code.

By using generator, you can write this:

Try {    = yield Ajax (' http://url-1 ', data1);     = Yield Ajax (' Http://url-2 ', data2);     = Yield Ajax (' http://url-3 ', data3);    Success (R3);} Catch (err) {    handle (err);}

The code that appears to be synchronous, is actually an asynchronous code.

JavaScript Learning Notes (13)--Generator (generator)

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.