Table of Contents
yield output value
Home Web Front-end JS Tutorial Detailed understanding of Generator function in JavaScript

Detailed understanding of Generator function in JavaScript

Mar 20, 2019 am 10:26 AM
javascript

This article brings you a detailed understanding of the Generator function in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article is about the summary and understanding of generator functions in ES6...

The definition of Generator function

In teacher Ruan Yifeng's The book says:
Generator function has multiple understanding angles. Syntactically, it can be understood first that the Generator function is a state machine that encapsulates multiple internal states. Executing the Generator function will return a traverser object. In other words, in addition to the state machine, the Generator function is also a traverser object generation function. The returned traverser object can traverse each state inside the Generator function in sequence.

My understanding:
The generator function can be understood as: the interior of the function is composed of multiple small functions, and the yield keyword is used to divide the interior of the function into multiple block areas; and when the function is executed , it will stop when it encounters yield, and output the expression result after yield (of course the next() method must be called externally); the next time the next() method is called, execution will start from where it stopped (this means The function has a memory function); if no yield is encountered again, it will be like a normal function. The return value of the function is an iterable object (traverser object); I like to call it iterable object, or traversable object ...

Let’s talk about the next() method of iterable objects (iterator)

function CreateIterator(iterator) {
    // 定义一个初始下标用来判断
    let nextIndex = 0;

    // 返回对象: 包含的next方法, 
    return {
        next: function () {
            // 返回一个对象: value是当前对象下标对应的值, done是是否遍历完成
            return nextIndex <p style="white-space: normal;"><strong>The use of generator functions</strong></p><pre class="brush:php;toolbar:false">generator生成器函数的使用:
function *fn() {
    代码1; 
    yield; 
    代码2;
}
普通函数: 执行到底
生成器函数: 遇到yield会暂停,交出执行权,下次执行从上次的停止的位置继续
生成器函数返回值为: 生成器对象
生成器对象.next()方法才能执行 函数体中的代码
// 可以解决函数回调嵌套的问题; 解决耗时操作
function *func() {
    // 请求数据.
    // yield ajax() 
    // 处理数据
} 
// generator函数本质上 分割成多个小函数来执行... yield关键字前后
// 遇到yield就暂停; 没有就往下执行...
// yield 起到了 暂停函数执行的作用
Copy after login

About the understanding of yield keyword

yield pass value

Detailed understanding of Generator function in JavaScript

yield output value

Detailed understanding of Generator function in JavaScript

## Give a chestnut:

     function *g2(x, y) {        
    let sum = x+y;
    yield sum; // sum是第一个输出结果
        
    let agv = sum / 2;
    yield agv; // agv 是第二个输出的结果
    
    return {"和": sum, "平均数": agv}; // 最后一个结果
}
    
let gg2 = g2(100, 20);        
console.log(gg2.next().value);  // 120
console.log(gg2.next().value);  // 60
console.log(gg2.next().value);  // { '和': 120, '平均数': 60 }
Copy after login

Application of Generator

Here is just a simple example, like the async function in ES7 that we usually use; he is the generator An application of functions; it is actually syntactic sugar for the Generator function.

Borrow an example from ES6 Getting Started: Two ways to read files

const fs = require('fs');

const readFile = function (fileName) {
  return new Promise(function (resolve, reject) {
    fs.readFile(fileName, function(error, data) {
      if (error) return reject(error);
      resolve(data);
    });
  });
};

// 1.使用生成器函数 读取文件
const gen = function* () {
  const f1 = yield readFile(__dirname + '/first.json');
  const f2 = yield readFile(__dirname + '/second.json');

  console.log(f1.toString());  // 没有输出; 因为 f1 拿到是一个 Iterator 对象 
  console.log(f2.toString());
};

// 使用 async + await 读取; 注意两种需配合使用
const asyncReadFile = async function () {
    const f1 = await readFile(__dirname + '/first.json');
    const f2 = await readFile(__dirname + '/second.json');

    console.log(f1.toString());  //async函数的返回值是 Promise 对象
    console.log(f2.toString());
};

gen(); // 没有值, 需要用 next()方法去取值
asyncReadFile() // 返回值 {"hello": "first"} {"hello": "second"}
Copy after login
So; let’s compare here; the async function replaces the asterisk (*) in the Generator function with async , replacing yield with await greatly facilitates our use.

We can use async await to implement usual asynchronous code...

For example, an ajax request in vue to obtain data

methods: {
    async getApi() {
        let res = await axios.get('url')
        // 这里的执行顺序是同步的...
        console.log(res)
    }
}
Copy after login
This article ends here It's all over. For more other exciting content, you can pay attention to the J

javaScript tutorial video column on the PHP Chinese website!

The above is the detailed content of Detailed understanding of Generator function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months 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 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

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.

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

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

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

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles