当前位置:网站首页>Asynchronous application of generator function
Asynchronous application of generator function
2022-07-07 15:42:00 【When can Xiaobai advance to success】
1、 traditional method
ES6 Before birth , The methods of asynchronous programming are as follows 4 Kind of :
- Callback function
- Event monitoring
- Release / subscribe
- Promise object
Generator Function will JavaScript Asynchronous programming takes a whole new phase .
2、 Basic concepts
(1) Asynchronous and synchronous ;
It can be understood that a task is not completed continuously , It can be understood that the task is divided into two sections , First paragraph , Then switch to other tasks , When you are ready, go back to the second paragraph .
(2) Callback function
Code to read files for processing :
fs.readFile('/etc/passwd','utf-8',function(err,data){
if(err)
throw err;
console.log(data);
})readFile The third parameter of is the callback function , Wait for the operating system to return /etc/passwd After file , The callback function will execute .
An interesting question : Why? Node The first parameter of the Convention callback function must be the error object err? The reason lies in , The implementation is divided into two parts , After the execution of the first paragraph , The context of the task is over . Errors thrown after this , Its original context has been unable to capture , Therefore, it can only be passed into the second segment as a parameter .
fs.readFile yes node.js Read files from Methods .
3、 coroutines
coroutines : Multiple tasks cooperate with each other , Complete asynchronous tasks .
Coprograms are a bit like functions , It's a bit like a thread . Its operation process is as follows :
- coroutines A Start execution .
- coroutines A Halfway through , Enter the pause state , The executive power is transferred to Xiecheng B in .
- ( After a while ), coroutines B Return of executive power .
- coroutines A Resume execution .
The co process of reading the file is written as follows :
function* asyncJob(){
//... Other code
var f = yield readFile(fileA);
//... Other code
}asyncJob It's a collaborative process , The mystery lies in yield command . It means when you execute here , The right of execution will be left to the other parties . namely yield Command is the dividing line between two asynchronous phases .
4、Generator Data exchange inside and outside function body
(1)next The return value of value The attribute is Generator Function to output data out
function test()
{
var g = gen(1);
console.log(g.next().value);// The function body transmits data outward ;
console.log(g.next(5).value);// Transfer data to the function body ;
}
function* gen(x){
var y = yield x+2;
return y;
}Running results :

In the above code , first next Methodical value Property to return the expression x=2 Value 3.
(2)next Method accept parameters , Enter data into the function body
the second next Method with parameters 5, This parameter can be passed in Generator function , As the return of the asynchronous task in the previous stage , Variables in the body of the function y receive . therefore , This step of value Property returns 5.
5、Generator Function error handling
Generator Error handling code can also be deployed in the function , Catch errors thrown outside of the function .
function test()
{
var g = gen(10);
let re = g.next().value;// The function body transmits data outward ;
if(re>10)
{
console.log(re);
g.throw("Error: The value is too large !");
}
}
function* gen(x)
{
try{
var y = yield x+2;
}catch(e){
console.log(e);
}
return y;
}Running results :

In the last line of the above code ,Generator Functions that use pointer objects outside thow Method can be thrown by the function body try...catch Code block capture . It means , The error code and the error handling code realize the separation of time and space , This is undoubtedly very important for asynchronous programming .
边栏推荐
- The difference between full-time graduate students and part-time graduate students!
- Getting started with webgl (3)
- 【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)
- Ctfshow, information collection: web13
- 【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
- Bye, Dachang! I'm going to the factory today
- Write a ten thousand word long article "CAS spin lock" to send Jay's new album to the top of the hot list
- leetcode 241. Different Ways to Add Parentheses 为运算表达式设计优先级(中等)
- Using eating in cocos Creator
- MySQL bit type resolution
猜你喜欢
![[quick start of Digital IC Verification] 22. Ahb-sramc of SystemVerilog project practice (2) (Introduction to AMBA bus)](/img/3f/40475f9f6e0fcd3f58c93164f65674.png)
[quick start of Digital IC Verification] 22. Ahb-sramc of SystemVerilog project practice (2) (Introduction to AMBA bus)

TypeScript 发布 4.8 beta 版本
![[quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)](/img/91/16a370ac41adc8fe31507765a82b0a.png)
[quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)

Spin animation of Cocos performance optimization

Guangzhou Development Zone enables geographical indication products to help rural revitalization

unnamed prototyped parameters not allowed when body is present

Typescript release 4.8 beta

2022 all open source enterprise card issuing network repair short website and other bugs_ 2022 enterprise level multi merchant card issuing platform source code
Implementation of crawling web pages and saving them to MySQL using the scrapy framework
![[follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code](/img/8d/a6d477a8679ca4f3885b1a7b542437.png)
[follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code
随机推荐
Using eating in cocos Creator
Points for attention in porting gd32 F4 series programs to gd32 F3 series
Super simple and fully automated generation super signature system (cloud Xiaoduo minclouds.com cloud service instance), free application in-house test app distribution and hosting platform, maintenan
[quick start of Digital IC Verification] 24. AHB sramc of SystemVerilog project practice (4) (AHB continues to deepen)
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
How to release NFT in batches in opensea (rinkeby test network)
【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
Connecting FTP server tutorial
postman生成时间戳,未来时间戳
STM32F103C8T6 PWM驱动舵机(SG90)
Unity之ASE实现卡通火焰
webgl_ Graphic transformation (rotation, translation, zoom)
How to build your own super signature system (yunxiaoduo)?
Ctfshow, information collection: web13
【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
众昂矿业:萤石继续引领新能源市场增长
【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)
【数字IC验证快速入门】23、SystemVerilog项目实践之AHB-SRAMC(3)(AHB协议基本要点)
[quickstart to Digital IC Validation] 20. Basic syntax for system verilog Learning 7 (Coverage Driven... Including practical exercises)
Summer safety is very important! Emergency safety education enters kindergarten