当前位置:网站首页>JS generator
JS generator
2022-06-30 04:09:00 【Runqing】
Basic use
Generator The function is ES6 An asynchronous programming solution provided by . Generator functions can pause while executing , After that, it can continue from the pause .
Generator function function There is an asterisk between the keyword and the function name ; Function body internal use yield expression , Define different internal states (yield In English, it means “ Produce ”)function* name([param[, param[, ... param]]]) { statements }
Calling a generator function does not immediately execute the statements in it , Instead, it returns a iterator ( iterator ) object .
When this iterator's next() The method was first ( follow-up ) Invocation time , The statements in it are executed to the first ( follow-up ) appear yield Up to ,yield Followed by the value to be returned by the iterator .
Or if you use yield*( There's an extra asterisk ), It means to transfer the execution right to another generator function ( The current generator is paused ).
next() Method returns an object , This object contains two properties :value and done,value Property indicates this time yield Return value of expression ,done Property is boolean type , Indicates whether the generator will have any follow-up information yield sentence , That is, whether the generator function has been executed and returned .
function * gen () {
let val
val = yield 1
console.log(`1:${
val}`)
val = yield 2
console.log(`2:${
val}`)
val = yield 3
console.log(`3:${
val}`)
}
var g = gen()
console.log(g.next()) // {value: 1, done: false}
console.log(g.next()) // {value: 2, done: false}
console.log(g.next()) // {value: 3, done: false}
console.log(g.next()) // {value: undefined, done: true}
yield The ginseng
call next() When the method is used , If parameters are passed in , Then this parameter will be passed to the previous execution yield Variables to the left of the statement , For example, in the following example x :
function *gen(){
yield 10;
x=yield 'foo';
yield x;
}
var gen_obj=gen();
console.log(gen_obj.next());// perform yield 10, return 10
console.log(gen_obj.next());// perform yield 'foo', return 'foo'
console.log(gen_obj.next(100));// take 100 To the previous one yield 'foo' Left value of , The perform x=100, return 100
console.log(gen_obj.next());// completion of enforcement ,value by undefined,done by true
Generator Object method :next、return、throw.
Generator.prototype.next()
// Returns a yield The value generated by the expression .
Generator.prototype.return()
// Returns the given value and ends the generator .
Generator.prototype.throw()
// Throw an error to the generator .
among ,next() See above for the method , Don't go into details . Let's take a brief look return and throw.
// return()
function* gen() {
yield 1;
yield 2;
yield 3;
}
var g = gen();
g.next(); // { value: 1, done: false }
g.return("foo"); // { value: "foo", done: true }
g.next(); // { value: undefined, done: true }
// If the pair is already in “ complete ” State generator calls return(value), Then the generator will remain in “ complete ” state .
// If no parameters are provided , Returns the value Properties and the last of the example .next() In the same way .
// If parameters are provided , The parameter will be set to return the of the object value The value of the property .
// throw()
function* gen() {
while(true) {
try {
yield 42;
} catch(e) {
console.log("Error caught!");
}
}
}
var g = gen();
g.next(); // { value: 42, done: false }
// Use throw Method throws an exception to the generator , This exception can usually be passed through try...catch Block to capture .
g.throw(new Error("Something went wrong")); // "Error caught!"
A generator function cannot be used as a constructor
function* f() {
}
var obj = new f; // throws "TypeError: f is not a constructor"
Examples of application scenarios
Luck draw : Return the result of a single execution each time
边栏推荐
- Knowledge - how to build rapport in sales with 3 simple skills
- Unity when entering a string in the editor, escape the input of characters
- 【云原生】AI云开发平台——AI Model Foundry介绍(开发者可免费体验AI训练模型)
- el-upload上传文件(手动上传,自动上传,上传进度)
- Do280 private warehouse persistent storage and chapter experiment
- 【论文阅读|深读】Role2Vec:Role-Based Graph Embeddings
- (03).NET MAUI实战 基础控件
- 接口测试--如何分析一个接口?
- Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
- A minimalist way to integrate databinding into activity/fragment
猜你喜欢

How to use FME to create your own functional software

Interface testing -- how to analyze an interface?

Node-RED系列(二八):基于OPC UA节点与西门子PLC进行通讯
![[punch in - Blue Bridge Cup] day 4--------- split ('') cannot be used. There is a space after the last number of test cases. Split ()](/img/00/3793a236ee37085cb47dbfa1f0dbff.jpg)
[punch in - Blue Bridge Cup] day 4--------- split ('') cannot be used. There is a space after the last number of test cases. Split ()

Solve the problem of Navicat connecting to the database

如何通过进程启动来分析和解决EasyCVR内核端口报错问题?

Day 12 advanced programming techniques

Geometric objects in shapely

【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码

El upload upload file (manual upload, automatic upload, upload progress)
随机推荐
[operation] MySQL query on May 24, 2022
Jour 9 Gestion des scripts et des ressources
UML diagrams and list collections
How to solve the problem of link hyperlinks when trying to link the database?
[operation] getting started with MySQL on May 23, 2022
解决navicat连接数据库遇到的问题
Node-RED系列(二八):基于OPC UA节点与西门子PLC进行通讯
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
[operation] MySQL query operation 2 on May 25, 2022
Smart use of bitmap to achieve 100 million level massive data statistics
Splicing strings with custom functions
dotnet-exec 0.5.0 released
I spent three years in a big factory outsourcing, which subverted my understanding!
[note] on May 27, 2022, MySQL is operated through pychart
El upload upload file (manual upload, automatic upload, upload progress)
Error Nova missingauthplugin: an auth plugin is required to determine endpoint URL
Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
第九天 脚本与资源管理
Technology sharing | broadcast function design in integrated dispatching
If you encounter problems when using spark for the first time, please ask for help