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

Front-end JavaScript housekeeper package.json

Table of contents 1. Required attributes 1. name ...

Basic principles of MySQL scalable design

Table of contents Preface 1. What is scalability?...

Detailed steps to install Nginx on Linux

1. Nginx installation steps 1.1 Official website ...

Why does using limit in MySQL affect performance?

First, let me explain the version of MySQL: mysql...

Summarize the User-Agent of popular browsers

1. Basic knowledge: Http Header User-Agent User A...

Install multiple versions of PHP for Nginx on Linux

When we install and configure the server LNPM env...

How to create an index on a join table in MySQL

This article introduces how to create an index on...

The use and methods of async and await in JavaScript

async function and await keyword in JS function h...

How to use CSS to achieve data hotspot effect

The effect is as follows: analyze 1. Here you can...

The difference between HTML iframe and frameset_PowerNode Java Academy

Introduction 1.<iframe> tag: iframe is an i...

A brief discussion on the $notify points of element

My original intention was to encapsulate the $not...

A brief summary of vue keep-alive

1. Function Mainly used to preserve component sta...

Introduction and tips for using the interactive visualization JS library gojs

Table of contents 1. Introduction to gojs 2. Gojs...

Briefly describe how to install Tomcat image and deploy web project in Docker

1. Install Tomcat 1. Find the tomcat image on Doc...

Two ways to implement text stroke in CSS3 (summary)

question Recently I encountered a requirement to ...