当前位置:网站首页>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 .
边栏推荐
- Background system sending verification code function
- 2.3 learning content
- D-snow halo solution
- 具有倍数关系的时钟切换
- obj集合转为实体集合
- MySQL giant pit: update updates should be judged with caution by affecting the number of rows!!!
- 16. [stm32] starting from the principle, I will show you the DS18B20 temperature sensor - four digit digital tube displays the temperature
- Six common transaction solutions, you sing, I come on stage (no best, only better)
- 开发中Boolean类型使用遇到的坑
- 【 note 】 résoudre l'erreur de code IDE golang
猜你喜欢

F. Min cost string problem solving Report

Parameter type setting error during batch update in project SQL

项目sql中批量update的时候参数类型设置错误

MySQL 巨坑:update 更新慎用影响行数做判断!!!

Data communication foundation - routing communication between VLANs

obj集合转为实体集合

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

ES6深入—ES6 Generator 函数
![19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)](/img/fe/8f59db28823290da8e9280df06673d.jpg)
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)

【 note 】 résoudre l'erreur de code IDE golang
随机推荐
SQL injection sqllabs (basic challenges) 1-10
D-snow halo solution
Definition of episodic and batch
【简记】解决IDE golang 代码飘红报错
定义严苛标准,英特尔Evo 3.0正在加速PC产业升级
五种常见的咨询公司谈判策略以及如何维护自己的利益
Quick completion guide for manipulator (IX): forward kinematics analysis
2.3 learning content
抽象类中子类与父类
Dataarts studio data architecture - Introduction to data standards
助力数字经济发展,夯实数字人才底座—数字人才大赛在昆成功举办
List uses stream flow to add according to the number of certain attributes of the element
Codasip adds verify safe startup function to risc-v processor series
19.[STM32]HC_SR04超声波测距_定时器方式(OLED显示)
Cs231n notes (medium) -- applicable to 0 Foundation
Query the latest record in SQL
Memo 00
Advanced level of static and extern
研发效能度量指标构成及效能度量方法论
Which keywords will conflict with the abstract keyword