Use Javascript Generators in Node. js for details, node. jsgenerators

Source: Internet
Author: User

Use Javascript Generators in Node. js for details, node. jsgenerators

Generators is a collaborative program (coroutine for short: coroutine) style in Javascript. It refers to the functions that can be paused and restored during execution, this function is configured with a star symbol in functi, such as function *. Some feature keywords in the function, such as yield and yield *.

function* generatorFn () { console.log('look ma I was suspended')}var generator = generatorFn() // [1]setTimeout(function () { generator.next() // [2]}, 2000)

[1] and [2] marked in the Code are explained as follows:

1. This is a generator that starts to pause. At this time, no console output is available.

2. By calling its next () method, this generator will run until it encounters the next yield keyword or return. Now we have the console output.

Let's look at another case:

function *generator() { console.log('Start!'); var i = 0; while (true) {  if (i < 3)   yield i++; }}var gen = generator();

The above code is similar to the first one, but the yield keyword is added in the generator function. When the above Code is called, it will not be executed immediately, but will be suspended for standby, so there will be no Start output. It is not executed until its next () call.

var ret = gen.next();// Start!console.log(ret);// {value: 0, done: false}

The above ret is the generator result. It has two attributes:

■ Value, yield value in the generator function,

■ Done, which indicates whether the generator function returns the result.

Continue with the Code as follows:

console.log(gen.next());// {value: 1, done: false}console.log(gen.next());// {value: 2, done: false}console.log(gen.next());// {value: undefined, done: true}

Generator has no xuanjicang in synchronous programming, which is especially suitable for asynchronous programming.

Generator has two features:

1. You can choose to jump out of a function, so that external code can decide when to jump back to the function for further execution.
2. asynchronous control.

Take a look at the following asynchronous code execution:

Var gen = generator (); console. log (gen. next (). value); setTimeout (function () {console. log (gen. next (). value); console. log ('step 1 ');}, 1000); console. log ('step 2 ');

The output is:

0
Step 2
1
Step 1

That is to say, it will not wait for the timer to end in setTimeout, but will directly continue the "second step" and will not be blocked in setTimeout.

Let's look at another piece of code:

function* channel () { var name = yield 'hello, what is your name?' // [1] return 'well hi there ' + name}var gen = channel()console.log(gen.next().value) // hello, what is your name? [2]console.log(gen.next('billy')) // well hi there billy [3]

You can also use *:

function* iter () { for (var i = 0; i < 10; i++) yield i}for (var val of iter()) { console.log(val) // outputs 1?—?9}

Common misunderstanding

Since I can pause the execution of a function, do I want to execute them in parallel? No, because Javascript is a single thread. If you want to improve performance, generator is not your dish.

For example, the following code executes the Fibonacci numbers respectively:

function fib (n) { var current = 0, next = 1, swap for (var i = 0; i < n; i++) {  swap = current, current = next  next = swap + next } return current} function* fibGen (n) { var current = 0, next = 1, swap for (var i = 0; i < n; i++) {  swap = current, current = next  next = swap + next  yield current }}

The performance results are as follows: (the higher the better)

Results:
Regular 1263899
Generator 37541

Generators shining points

Generators simplifies the complexity of functions in JavaScript.

Lazy assignment

Although lazy assignment can be implemented using the closure of JS, yield can be greatly simplified. by pausing and restoring it, we can obtain the value when we need it, for example, the above Figen function can pull a new value as needed:

Var fibIter = fig (20) var next = fig. next () console. log (next. value) setTimeout (function () {var next = fibIter. next () console. log (next. value)}, 2000) of course, The for loop is also used: it is still lazy assignment for (var n of fiber Gen (20) {console. log (n )}

Infinite sequence

Because the assignment can be left empty, some Haskell tricks may be performed, similar to infinite sequences. Here yield can be an infinite number of sequences.

function* fibGen () { var current = 0, next = 1, swap while (true) {  swap = current, current = next  next = swap + next  yield current }}

Let's take a look at the lazy assignment of a Fibonacci number stream and ask it to return the first Fibonacci number after 5000:

for (var num of fibGen()) { if (num > 5000) break}console.log(num) // 6765

Asynchronous Process Control

How does one Implement Asynchronous Process Control Using generators? The most common is various promise library packages?

In the Node field, everything is related to callback. This is our low-level asynchronous function. We can use generators to establish a communication channel and write asynchronous code in a synchronous programming style.

run(function* () { console.log("Starting") var file = yield readFile("./async.js") // [1] console.log(file.toString())})

Note 1 indicates that the program will continue after async. js returns the result.

Genify is a framework that brings generators into the normal programming environment. It is used as follows:

Run the following code to install npm install genify:

Var Q = require ('q'); var fs = require ('fs'); var genify = require ('genify '); // wrap your object into genify functionvar object = genify ({concatFiles: function * (file1, file2, outFile) {file1 = yield Q. nfcall (fs. readFile, file1); file2 = yield Q. nfcall (fs. readFile, file2); var concated = file1 + file2; yield Q. nfcall (fs. writeFile, outFile, concated); return concated ;}}); // concatFiles is a generat Or function, which uses the power of generator. Object. concatFiles ('. /somefile1.txt ','. /somefile2.txt ','. /concated.txt '). then (function (res) {// do something with result}, function (err) {// do something with error });

The above section details how to use Javascript Generators in Node. js is all the content that I have shared with you. I hope you can give me a reference and support me a lot.

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.