当前位置:网站首页>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 .
边栏推荐
- Query the latest record in SQL
- Write a go program with vscode in one article
- 【网易云信】超分辨率技术在实时音视频领域的研究与实践
- Advanced level of static and extern
- 程序员如何提升自己的格局?
- ES6深入—ES6 Class 类
- sql中查询最近一条记录
- This article takes you through the addition, deletion, modification and query of JS processing tree structure data
- Parameter type setting error during batch update in project SQL
- go语言编程规范梳理总结
猜你喜欢
The difference between abstract classes and interfaces
【簡記】解决IDE golang 代碼飄紅報錯
Mistakes made when writing unit tests
How difficult is it to pass the certification of Intel Evo 3.0? Yilian technology tells you
CISP-PTE之SQL注入(二次注入的应用)
The OBD deployment mode of oceanbase Community Edition is installed locally
19.[STM32]HC_ SR04 ultrasonic ranging_ Timer mode (OLED display)
Fundamentals of data communication - Principles of IP routing
Five common negotiation strategies of consulting companies and how to safeguard their own interests
Six common transaction solutions, you sing, I come on stage (no best, only better)
随机推荐
ES6深入—async 函数 与 Symbol 类型
异常com.alibaba.fastjson.JSONException: not match : - =
Vulnhub-Moneybox
CODING DevSecOps 助力金融企业跑出数字加速度
Data communication foundation - dynamic routing protocol rip
Subclasses and superclasses of abstract classes
Arduino控制微小的六足3D打印机器人
Lesson 4 knowledge summary
Example of lvgl display picture
单商户 V4.4,初心未变,实力依旧!
Virtual base class (a little difficult)
CSDN I'm coming
Appium自动化测试基础 — APPium基础操作API(一)
wyt 。。
Mistakes made when writing unit tests
Record the pits encountered in the raspberry pie construction environment...
Noi / 1.5 37: mercenaries
16. [stm32] starting from the principle, I will show you the DS18B20 temperature sensor - four digit digital tube displays the temperature
Memo 00
六种常用事务解决方案,你方唱罢,我登场(没有最好只有更好)