当前位置:网站首页>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 .
边栏推荐
猜你喜欢
![18.[stm32] read the ROM of DS18B20 temperature sensor and realize multi-point temperature measurement](/img/e7/4f682814ae899917c8ee981c05edb8.jpg)
18.[stm32] read the ROM of DS18B20 temperature sensor and realize multi-point temperature measurement

ES6深入—ES6 Class 类

Summary of the third class

基于OpenHarmony的智能金属探测器

Use of set tag in SQL

开发中Boolean类型使用遇到的坑

Data communication foundation OSPF Foundation

Data communication foundation smart_ Link_&_ Monitor_ Link

Appium automation test foundation - appium basic operation API (II)

Intelligent metal detector based on openharmony
随机推荐
Dataarts studio data architecture - Introduction to data standards
The OBD deployment mode of oceanbase Community Edition is installed locally
示例项目:简单的六足步行者
Example of lvgl display picture
The visual experience has been comprehensively upgraded, and Howell group and Intel Evo 3.0 have jointly accelerated the reform of the PC industry
ES6深入—ES6 Generator 函数
Summary of the second lesson
抽象类中子类与父类
17. [stm32] use only three wires to drive LCD1602 LCD
Fundamentals of data communication - Principles of IP routing
通过的英特尔Evo 3.0整机认证到底有多难?忆联科技告诉你
How difficult is it to pass the certification of Intel Evo 3.0? Yilian technology tells you
OceanBase社区版之OBD方式部署方式本地安装
Value series solution report
Data communication foundation - Ethernet port mirroring and link aggregation
Li Kou today's question -729 My schedule I
lv_ font_ Conv offline conversion
Basic JSON operations of MySQL 5.7
Intelligent metal detector based on openharmony
CODING DevSecOps 助力金融企业跑出数字加速度