Liaoche JS Tutorial Note 6 Generator A pit read Python in the back pits

Source: Internet
Author: User

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.

ES6 define the generator standard Buddy borrowed from the Python generator concept and syntax, if you are familiar with Python generator, then ES6 generator is a piece of cake. If you're not familiar with Python, hurry up and make a python tutorial!.

Let's review the concept of function first. 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 r = foo(1); // 调用foo函数

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

Generator is similar to a function and is defined as follows:

function* foo(x) {    yield x + 1;    yield x + 2; return x + 3;}

Generator and functions are different, generator by function* definition (note the number of extra * numbers), and, in addition to return statements, can also be yield returned multiple times.

Most of the students immediately faint, generator is able to return multiple "function"? What's the use of returning multiple times?

Just give me a chestnut.

For example, we take a famous Fibonacci sequence, which 0 1 begins with:

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, arr = [0, 1]; while (arr.length < max) { t = a + b; a = b; b = t; arr.push(t); } return arr;}// 测试:fib(5); // [0, 1, 1, 2, 3]fib(10); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

function can only be returned once, so one must be returned Array . However, if you switch to generator, you can return one number at a time, returning multiple times. Rewrite with generator as follows:

function* fib(max) {    var        t,        a = 0,        b = 1,        n = 1; while (n < max) { yield a; t = a + b; a = b; b = t; n ++; } return a;}

Direct call Try:

fib(5); // fib {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}

Calling a generator directly is not the same as calling a function, fib(5) just creating a generator object and not executing it.

There are two methods to call the generator object, one is to constantly call the generator object next() :

var f = fib (5); F.Next ();//{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: true}              

next()The generator method executes the code, and then yield x; returns an object each time it is encountered {value: x, done: true/false} , and then "pauses". Returns the value yield return value that done indicates whether the generator has been executed at the end. If it is done true , it value is return the return value.

When executed done true , the generator object is fully executed, and no further calls next() are made.

The second method is to iterate the generator object directly with a for ... of loop, which does not require our own judgment done :

for (var x of fib(5)) {    console.log(x); // 依次输出0, 1, 1, 2, 3}

What is the use of generator compared to normal functions?

Because generator can be returned multiple times during execution, it looks like a function that remembers the state of execution, and with this, writing a generator can implement functionality that requires an object-oriented implementation. For example, use an object to save the state, so write:

var fib = {    a: 0,    b: 1,    n: 0,    max: 5, next: function () { var r = this.a, t = this.a + this.b; this.a = this.b; this.b = t; if (this.n < this.max) { this.n ++; return r; } else { return undefined; } }};

It is quite tedious to use the properties of the object to save the state.

Another great benefit of generator is that it turns the async callback code into a "synchronous" code. This benefit will not be realized until after learning Ajax in the back.

There is no generator before the Dark ages, using Ajax to write code like this:

ajax(‘http://url-1‘, data1, function (err, result) {    if (err) { return handle(err); } ajax(‘http://url-2‘, data2, function (err, result) { if (err) { return handle(err); } ajax(‘http://url-3‘, data3, function (err, result) { if (err) { return handle(err); } return success(result); }); });});

The more callbacks, the more ugly the code.

With the good times of generator, you can write this with Ajax:

try {    r1 = yield ajax(‘http://url-1‘, data1);    r2 = yield ajax(‘http://url-2‘, data2); r3 = yield ajax(‘http://url-3‘, data3); success(r3);}catch (err) { handle(err);}

The code appears to be synchronous, and the actual execution is asynchronous.

Practice

To generate an auto-increment ID, you can write a next_id() function:

var current_id = 0;function next_id() { current_id ++; return current_id;}

Liaoche JS Tutorial Note 6 Generator A pit read Python in the back pits

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.