Home Web Front-end JS Tutorial Detailed explanation of using Javascript Generators in Node.js_javascript tips

Detailed explanation of using Javascript Generators in Node.js_javascript tips

May 16, 2016 pm 03:01 PM
generators javascript node.js

Generators are a coroutine (coroutine for short: coroutine) style of Javascript. They refer to functions that can be paused and then resumed during execution. The function is in the functi with an asterisk symbol such as function*, function There are some characteristic keywords such as yield and yield*.

function* generatorFn () {

 console.log('look ma I was suspended')

}

var generator = generatorFn() // [1]

setTimeout(function () {

 generator.next() // [2]

}, 2000)
Copy after login

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

1. This is a generator started in pause mode. There is no console output at this time.

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

Look at another case:

function *generator() {

 console.log('Start!');

 var i = 0;

 while (true) {

  if (i < 3)

   yield i++;

 }

}
var gen = generator();
Copy after login

The above code is similar to the first one, except that the yield keyword is added to the generator function. When the above code is called, it will not be executed immediately, but will be suspended and on 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}
Copy after login

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

■value, the yield value in the generator function,

■done, this is a flag indicating whether the generator function returns.

The continuation code is 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}
Copy after login

Generator has no mystery in synchronous programming, and is especially suitable for asynchronous programming.

generator has two characteristics:

1. You can choose to jump out of a function and let the external code decide when to jump back to this function to continue execution.
2. Ability to perform asynchronous control.

Look at the asynchronous execution code below:

var gen = generator();

console.log(gen.next().value);

setTimeout(function() {

 console.log(gen.next().value);

 console.log('第一步');

}, 1000);

console.log('第二步');
Copy after login

The output is:

0
Step 2
1
The first step

In other words, you will not wait for the end of the timer in setTimeout, but continue directly to the "second step" and will not be blocked in setTimeout.

Look at another piece of code:

function* channel () {

 var name = yield 'hello, what is your name&#63;' // [1]

 return 'well hi there ' + name

}

var gen = channel()

console.log(gen.next().value) // hello, what is your name&#63; [2]

console.log(gen.next('billy')) // well hi there billy [3]
Copy after login

You can also use *:
when traversing

function* iter () {

 for (var i = 0; i < 10; i++) yield i

}

for (var val of iter()) {

 console.log(val) // outputs 1&#63;—&#63;9

}
Copy after login

Common misunderstandings

Since I can pause the execution of a function, should I let them execute in parallel? No, because Javascript is single-threaded, and if you are looking to improve performance, generators are not your cup of tea.

For example, the following code executes 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

 }

}
Copy after login

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

results:
regular 1263899
generator 37541

Generators shine

Generators can simplify the complexity of functions in JavaScript.

Lazy assignment

Although lazy assignment can be implemented using JS closures, using yield will greatly simplify it. By pausing and resuming, we can get the value when we need it. For example, the fibGen function above can pull it when we need it. New value:

var fibIter = fibGen(20)

var next = fibIter.next()

console.log(next.value)

setTimeout(function () {

 var next = fibIter.next()

 console.log(next.value)

},2000)

当然还使用for循环:依然是懒赋值

for (var n of fibGen(20) {

 console.log(n)

}
Copy after login

Infinite Sequence

Because lazy assignment is possible, it is possible to perform some Haskell tricks, similar to infinite sequences. Here you can yield an infinite number of sequences.

function* fibGen () {

 var current = 0, next = 1, swap

 while (true) {

  swap = current, current = next

  next = swap + next

  yield current

 }

}
Copy after login

Let’s 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
Copy after login

Asynchronous process control

Use generators to implement asynchronous process control. The most common ones are various promise library packages. So how does it work?

In the field of Node, everything is related to callbacks, which are our low-level asynchronous functions. We can use generators to establish a communication channel and write asynchronous code using a synchronous programming style.

run(function* () {

 console.log("Starting")

 var file = yield readFile("./async.js") // [1]

 console.log(file.toString())

})
Copy after login

Comment 1 indicates that the program will wait for async.js to return the result before continuing.

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

npm install genify to install, the code is as follows:

var Q = require('q');

var fs = require('fs');

var genify = require('genify');

 

// wrap your object into genify function

var 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是一个generator函数,它使用generator强大能力。

object.concatFiles('./somefile1.txt', './somefile2.txt', './concated.txt').then(function (res) {

 // do something with result

}, function (err) {

 // do something with error

});
Copy after login

The above detailed explanation of using Javascript Generators in Node.js is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles