当前位置:网站首页>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 .
边栏推荐
- 异常com.alibaba.fastjson.JSONException: not match : - =
- I'm fat, huh
- Advanced level of static and extern
- Boost the development of digital economy and consolidate the base of digital talents - the digital talent competition was successfully held in Kunming
- 抽象类中子类与父类
- SQL injection sqllabs (basic challenges) 11-20
- MySQL table field adjustment
- 具有倍数关系的时钟切换
- 修改pyunit_time使得其支持‘xx~xx月’的时间文本
- The computer is busy, and the update is a little slow
猜你喜欢
五种常见的咨询公司谈判策略以及如何维护自己的利益
16. [stm32] starting from the principle, I will show you the DS18B20 temperature sensor - four digit digital tube displays the temperature
sql中set标签的使用
Data communication foundation - Ethernet port mirroring and link aggregation
vulnhub-FirstBlood
Use of set tag in SQL
一文搞定vscode编写go程序
Codasip为RISC-V处理器系列增加Veridify安全启动功能
Data communication foundation - routing communication between VLANs
六种常用事务解决方案,你方唱罢,我登场(没有最好只有更好)
随机推荐
OSI seven layer model
ES6深入—ES6 Generator 函数
记一次'非常诡异'的云安全组规则问题排查过程
obj解析为集合
list使用Stream流进行根据元素某属性数量相加
18.[STM32]读取DS18B20温度传感器的ROM并实现多点测量温度
Appium自动化测试基础 — APPium基础操作API(一)
Boost the development of digital economy and consolidate the base of digital talents - the digital talent competition was successfully held in Kunming
21.[STM32]I2C协议弄不懂,深挖时序图带你编写底层驱动
【 note 】 résoudre l'erreur de code IDE golang
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)
Information collection of penetration test
List de duplication and count the number
Detailed explanation of C language branch statements
verilog实现计算最大公约数和最小公倍数
19.[STM32]HC_SR04超声波测距_定时器方式(OLED显示)
Background system sending verification code function
The computer is busy, and the update is a little slow
CISP-PTE之PHP伪协议总结
MySQL table field adjustment