Introduction and use of Javascript generator

Introduction and use of Javascript generator

What is a generator?

A generator is some code that runs inside a function.

  • After returning the value, it will pause itself and -
  • The caller can ask to cancel the pause and return another value

This "return" is not a traditional return from a function. So it is given a special name - yield.

Generator syntax varies from language to language. Javascript's generator syntax is similar to PHP's, but it's different enough that if you expect them to work the same, you'll end up being very confused.

In javascript, if you want to use a generator, you need to:

  • Defining special generator functions
  • Call this function to create a generator object
  • Use the generator object in a loop or call its next method directly.

We start with this simple program and follow each of the steps below:

// File: sample-program.js
function *createGenerator() {
 for(let i=0;i<20;i++) {
 yield i
 }
}

const generator = createGenerator()

console.log(generator.next())
console.log(generator.next())

If you run this code, you will get the following output:

$ node sample-program.js

{ value: 0, done: false }
{ value: 1, done: false }

Let me explain how the program works.

Generator Functions

First, there is the definition of the generator function in the code:

function* createGenerator() {
 for(let i=0;i<20;i++) {
 yield i
 }
}

The * after function tells JavaScript that this is a generator function. The following are all valid definitions of generator functions.

function*createGenerator
function* createGenerator
function *createGenerator

The * is not part of the function name. Instead, the function* notation defines a generator.

Calling the generator function

After defining the generator function, we call it a function of some other name.

// NOTE: When called, there is no *. * is not part of the function name // `function *` is the symbol used to define a generator function const generator = createGenerator()

But remember: the createGenerator function has no return value. This is because generator functions don't have a traditional return value. In contrast, when you call a generator function directly, it always returns an instantiated Generator object.

This generator object has a next method. Calling next will run the code inside the generator function.

function* createGenerator() {
 for(let i=0;i<20;i++) {
  yield i
 }
}

This is important enough to call it again. Calling a generator function directly does not run any code in the generator function. Instead, a generator object is created. It calls next on the generator object, which in turn calls the code in the generator function.

The first time next is called on a generator object, the code inside runs until a yield statement is encountered. Once a yield is reached, javascript will pause execution of that code, and next will return (give you, or yield) an object containing the value in the yield line.

When you call next a second time (or third, fourth, or more times), the code will be unpaused and continue running (where it left off on the last call). The variable (i in this case) will retain its value. When the code reaches another yield statement, the function pauses again and returns an object containing the yielded value.

That's why we call next twice.

console.log(generator.next())
console.log(generator.next())

You will get the following output:

{ value: 0, done: false }
{ value: 1, done: false }

Once the code in the generator function has finished executing, any future calls to next will return an object with a value of undefined and done set to true.

{ value: undefined, done: true }

Generators and loops

Although it is possible to call next manually on a generator object, we mainly want to use it in a loop. Take a look at this slightly modified program.

// File: sample-program.js
@highlightsyntax@jscript
function *createGenerator() {
 for(let i=0;i<5;i++) {
 yield i
 }
}

const generator = createGenerator()
for(const value of generator) {
 console.log(value)
}

When a generator object is used in a for...of loop, each time through the loop next is called on the generator object and the variable (value above) is filled with the produced value. Running the program will output the following:

$ node sample-program.js
0
1
2
3
4

In the next article, we'll take a closer look at the for ... of loop and explore how JavaScript has a built-in way to loop over any object in JavaScript.

Summarize

This is the end of this article about Javascript Generator. For more relevant Javascript Generator content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Generators in JavaScript ES6
  • Why JS says async/await is the syntax sugar of generator
  • In-depth explanation of the Generator function in js
  • js uses generator function to synchronously execute ajax tasks
  • How to use Generator in JavaScript
  • In-depth understanding of js generator data types
  • Detailed explanation of ES6 generator data type in JavaScript
  • A brief discussion on the use of Generator and Iterator in JavaScript
  • A brief analysis of JavaScript arrow function generator Date JSON
  • Using Javascript Generators in Node.js

<<:  Friendly Alternatives to Find Tool in Linux

>>:  Detailed explanation of performance monitoring of MySQL server using Prometheus and Grafana

Recommend

The whole process of node.js using express to automatically build the project

1. Install the express library and generator Open...

In-depth explanation of the impact of NULL on indexes in MySQL

Preface I have read many blogs and heard many peo...

An article to help you understand Js inheritance and prototype chain

Table of contents Inheritance and prototype chain...

HTML Language Encyclopedia

123WORDPRESS.COM--HTML超文本标记语言速查手册<!-- --> !D...

Linux directory switching implementation code example

Switching files is a common operation in Linux. W...

About IE8 compatibility: Explanation of the X-UA-Compatible attribute

Problem description: Copy code The code is as fol...

Docker removes abnormal container operations

This rookie encountered such a problem when he ju...

Docker deploys mysql remote connection to solve 2003 problems

Connecting to MySQL Here I use navicat to connect...

Vue+flask realizes video synthesis function (drag and drop upload)

Table of contents We have written about drag and ...

Tutorial on how to deploy LNMP and enable HTTPS service

What is LNMP: Linux+Nginx+Mysql+(php-fpm,php-mysq...

Detailed explanation of the pitfalls of Apache domain name configuration

I have never used apache. After I started working...

Summary of common MySQL commands

Set change mysqlroot password Enter the MySQL dat...

IIS7 IIS8 http automatically jumps to HTTPS (port 80 jumps to port 443)

IIS7 needs to confirm whether the "URL REWRI...