search
HomeWeb Front-endJS TutorialDetailed explanation of using Javascript Generators in Node.js_javascript tips

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)

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();

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}

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}

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('第二步');

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]

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

}

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

 }

}

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)

}

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

 }

}

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

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())

})

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

});

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
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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.