当前位置:网站首页>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
边栏推荐
- Error in conditional filter (if) syntax in sum function in SQL Server2005
- GIS related data
- 尝试链接数据库时出现链接超时报错,如何解决?
- 01 backpack, dynamic planning
- Project safety and quality
- When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
- Use ideal to connect to the database. The results show some warnings. How to deal with this part
- [Thesis reading | deep reading] role2vec:role based graph embeddings
- [cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
- 数据链路层详解
猜你喜欢

The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure

Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool

Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview

Postman learning sharing

How to analyze and solve the problem of easycvr kernel port error through process startup?
![[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 ()
![[note] Introduction to data analysis on June 7, 2022](/img/8b/9119bfdd10227f5c29ca2ece192880.png)
[note] Introduction to data analysis on June 7, 2022

DBT product initial experience

(03). Net Maui actual combat basic control
![[punch in - Blue Bridge Cup] day 5 --- lower() small](/img/b5/21f51a7416c72c299cc59192a33b3a.jpg)
[punch in - Blue Bridge Cup] day 5 --- lower() small
随机推荐
If you encounter problems when using spark for the first time, please ask for help
Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
mysql更新数组形式的json串
[image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code
[operation] getting started with MySQL on May 23, 2022
Solve the problem of Navicat connecting to the database
I get n offers in two months. I don't have any difficult interviewers here
如何利用FME 创建自己的功能软件
[note] on May 27, 2022, MySQL is operated through pychart
节点CODE相同会导致数据重复
如何通过进程启动来分析和解决EasyCVR内核端口报错问题?
Day 11 script and game AI
The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database
An error occurs when sqlyog imports the database. Please help solve it!
Share an example of a simple MapReduce method using a virtual machine
Introduction to cloud native + container concept
Radiant energy, irradiance and radiance
lego_loam 代码阅读与总结
尝试链接数据库时出现链接超时报错,如何解决?
云原生——Web实时通信技术之Websocket