当前位置:网站首页>ES6 drill down - ES6 generator function
ES6 drill down - ES6 generator function
2022-07-05 16:04:00 【Braised snapper with orange cat】
List of articles
Preface
ES6 Added Generator function , Can pass yield keyword , Suspend the execution flow of a function , Thus, the execution process can be changed , Or you can pause or delay execution , This provides a solution for asynchronous programming .
The basic usage will be explained in this article .
One 、Generator Function composition
Generator There are two aspects that are different from ordinary functions :
function Back , There is a prefix before the function name * ;
Inside the function are yield expression .
among * Used to represent Generator function ,yield Used to define the internal state of a function .
function* call() {
console.log("first");
yield "1";
console.log("second");
yield "2";
console.log("third");
return "3";
}
Two 、Generator Function execution mechanism
Use Generator function , Like a normal function , Is to add (), however Generator Functions do not execute immediately like ordinary functions , Instead, it will return a pointer , This pointer points to the internal state of the object , So call the traverser object Iterator Of next Method , The pointer starts at the head of the function or where it was last stopped .
f.next();
// one
// {value: "1", done: false}
f.next();
// two
// {value: "2", done: false}
f.next();
// three
// {value: "3", done: true}
f.next();
// {value: undefined, done: true}
The detailed explanation is as follows :
First call next When the method is used , from Generator The head of the function starts executing , First it's printed first, Execute to yield Just stop , And will yield Value of the trailing expression ‘1’, As a return object value Property value , At this time, the function has not finished executing , Return object's done The property value is false.
Second call next When the method is used , Just like the first time .
Third call next When the method is used , First it's printed third, Then the return operation of the function is performed , And will return The value of the following expression , As a return object value Property value , At this point, the function has ended , therefore done The property value is true.
Last call next When the method is used , At this point, the function has been executed , So back value The property value is undefined ,done The property value is true. If you perform the third step , No, return In words , Go straight back {value: undefined, done: true}.
Create name as es6gen4.js The file of , And enter the following code .
function* call() {
console.log("first");
yield "1";
console.log("second");
yield "2";
console.log("third");
return "3";
}
var f = call();
f.next();
f.next();
f.next();
f.next();
Input... At the terminal node es6gen4.js function , The results are shown below :
3、 ... and 、 Function returns the method of the iterator object
next Method
Routine situation ,next When the method does not pass in parameters ,yield The return value of the expression is undefined. When next When passing in parameters , This parameter will be used as the previous step yield The return value of .
function* make2Parameter() {
console.log(" Start ");
var x = yield "2";
console.log(" first :" + x);
var y = yield "3";
console.log(" the second :" + y);
console.log(" All is :" + (x + y));
}
next The situation of not transmitting parameters is as follows :
var cost = make2Parameter();
cost.next();
// Start
// {value: "2", done: false}
cost.next();
// first :undefined
// {value: "3", done: false}
cost.next();
// the second :undefined
// All is :NaN
// {value: undefined, done: true}
next Parameter transmission :
var cost2 = make2Parameter();
cost2.next(10);
// Start
// {value: "2", done: false}
cost2.next(20);
// first :20
// {value: "3", done: false}
cost2.next(30);
// the second :30
// All :50
// {value: undefined, done: true}
establish The name is es6gen5.js The file of , And enter the following code .
function* make2Parameter() {
console.log(" Start ");
var x = yield "2";
console.log(" first :" + x);
var y = yield "3";
console.log(" the second :" + y);
console.log(" All is :" + (x + y));
}
var cost = make2Parameter();
cost.next();
// Start
// {value: "2", done: false}
cost.next();
// first :undefined
// {value: "3", done: false}
cost.next();
// the second :undefined
// All is :NaN
// {value: undefined, done: true}
var cost2 = make2Parameter();
cost2.next(10);
// Start
// {value: "2", done: false}
cost2.next(20);
// first :20
// {value: "3", done: false}
cost2.next(30);
// the second :30
// All :50
// {value: undefined, done: true}
The operation results are as follows :
Besides using next, You can also use for… of Loop traversal Generator Function production Iterator object .
return Method
return Method returns the given value , And end the traversal Generator function .return Method provides parameters , Returns the parameter ; When no parameters are provided , return undefined.
function* call() {
yield 1;
yield 2;
yield 3;
}
var f = call();
f.next();
// {value: 1, done: false}
f.return("foo");
// {value: "foo", done: true}
f.next();
// {value: undefined, done: true}
throw Method
throw The method can be used again Generator An exception is thrown outside the function body , Then capture inside the function body .
Another example :
var d = function* () {
try {
yield;
} catch (e) {
console.log(" Catch the errors inside ", e);
}
};
var i = d();
i.next();
try {
i.throw("a");
i.throw("b");
} catch (e) {
console.log(" Catch external errors ", e);
Create name as es6gen6.js The file of , And enter the following code .
var d = function* () {
try {
yield;
} catch (e) {
console.log(" Catch the errors inside ", e);
}
};
var i = d();
i.next();
try {
i.throw("a");
i.throw("b");
} catch (e) {
console.log(" Catch external errors ", e);
}
The operation results are as follows :
The traverser object threw two errors , The first to be Generator Function internal capture , The second is because of the... Inside the function body catch The function has been executed , This error will no longer be caught , So this error is thrown Generator The body of the function , Outside the body of the function catch Capture .
yield* expression
yield* Expressions are used to express yield Returns a traverser object , Used in Generator Internal function , Call another Generator function .
function* callA() {
console.log("callA: " + (yield));
}
function* callerB() {
while (true) {
yield* callA();
}
}
const callerObj = callerB();
callerObj.next();
callerObj.next("first");
callerObj.next("second");
Create name as es6gen7.js The file of , And enter the following code .
function* callA() {
console.log("callA: " + (yield));
}
function* callerB() {
while (true) {
yield* callA();
}
}
const callerObj = callerB();
callerObj.next();
callerObj.next("first");
callerObj.next("second");
The operation effect is as follows :
The above case code can be replaced by the following code ( The effect is the same ):
// Equate to
function* callerB() {
while (true) {
for (var value of callA) {
yield value;
}
}
}
Four 、 Use scenarios
Realization Iterator
For not having Iterator The object of the interface provides traversal methods .
function* objEnter(obj) {
const propKeys = Reflect.ownKeys(obj);
for (const propKey of propKeys) {
yield [propKey, obj[propKey]];
}
}
const jane = {
first: " Small A", last: " Big D" };
for (const [key, value] of objEnter(jane)) {
console.log(`${
key}: ${
value}`);
}
// first: Small A
// last: Big D
The complete case is as follows :
establish The name is es6gen8.js The file of . Enter the following code :
function* objEnter(obj) {
const propKeys = Reflect.ownKeys(obj);
for (const propKey of propKeys) {
yield [propKey, obj[propKey]];
}
}
const jane = {
first: " Small A", last: " Big D" };
for (const [key, value] of objEnter(jane)) {
console.log(`${
key}: ${
value}`);
}
// first: Small A
// last: Big D
Running effect :
Reflect.ownKeys() Returns all properties of the object , Whether the attribute is enumerable or not , Include Symbol. javascript Original is not available Iterator The interface can't go through for… of Traverse . It's used here Generator Function plus Iterator Interface , So you can traverse jane Object .
summary
This paper introduces ES6 Generator The concept and use of functions . In order to pass the yield keyword , Suspend the execution flow of a function , It makes it possible to change the execution process , So as to provide a solution for asynchronous programming .
边栏推荐
- Definition of episodic and batch
- OSI seven layer model
- Advanced level of static and extern
- CISP-PTE之SQL注入(二次注入的应用)
- Verilog realizes the calculation of the maximum common divisor and the minimum common multiple
- 写单元测试的时候犯的错
- Memo 00
- 事务回滚异常
- The visual experience has been comprehensively upgraded, and Howell group and Intel Evo 3.0 have jointly accelerated the reform of the PC industry
- Summary of the third class
猜你喜欢

我们为什么要学习数学建模?

Analytic hierarchy process of mathematical modeling (including Matlab code)

The visual experience has been comprehensively upgraded, and Howell group and Intel Evo 3.0 have jointly accelerated the reform of the PC industry

OceanBase社区版之OBD方式部署方式本地安装

一文搞定vscode编写go程序

Defining strict standards, Intel Evo 3.0 is accelerating the upgrading of the PC industry

Data communication foundation - Ethernet port mirroring and link aggregation

Replknet: it's not that large convolution is bad, but that convolution is not large enough. 31x31 convolution. Let's have a look at | CVPR 2022

开发中Boolean类型使用遇到的坑
![19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)](/img/fe/8f59db28823290da8e9280df06673d.jpg)
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)
随机推荐
示例项目:简单的六足步行者
Xiao Sha's arithmetic problem solving Report
Definition of episodic and batch
机械臂速成小指南(九):正运动学分析
F. Weights assignment for tree edges problem solving Report
Go language programming specification combing summary
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)
超分辨率技术在实时音视频领域的研究与实践
基于OpenHarmony的智能金属探测器
Virtual base class (a little difficult)
RepLKNet:不是大卷积不好,而是卷积不够大,31x31卷积了解一下 | CVPR 2022
Data communication foundation - dynamic routing protocol rip
18.[stm32] read the ROM of DS18B20 temperature sensor and realize multi-point temperature measurement
The visual experience has been comprehensively upgraded, and Howell group and Intel Evo 3.0 have jointly accelerated the reform of the PC industry
Exception com alibaba. fastjson. JSONException: not match : - =
Batch update in the project
Modify PyUnit_ Time makes it support the time text of 'xx~xx months'
MySQL 巨坑:update 更新慎用影响行数做判断!!!
20. [stm32] realize the function of intelligent garbage can by using ultrasonic module and steering gear
Background system sending verification code function