当前位置:网站首页>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 .
边栏推荐
- Unity之ASE实现全屏风沙效果
- How to release NFT in batches in opensea (rinkeby test network)
- jacoco代码覆盖率
- OpenGL common functions
- Points for attention in porting gd32 F4 series programs to gd32 F3 series
- Pit avoidance: description of null values in in and not in SQL
- Gd32 F3 pin mapping problem SW interface cannot be burned
- Bye, Dachang! I'm going to the factory today
- The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service
- Wechat applet 01
猜你喜欢
2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
What is Base64?
[deep learning] image hyperspectral experiment: srcnn/fsrcnn
MongoD管理数据库的方法介绍
The download button and debug button in keil are grayed out
Starting from 1.5, build a microservice framework link tracking traceid
[deep learning] semantic segmentation experiment: UNET network /msrc2 dataset
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
【数字IC验证快速入门】26、SystemVerilog项目实践之AHB-SRAMC(6)(APB协议基本要点)
知否|两大风控最重要指标与客群好坏的关系分析
随机推荐
【OBS】RTMPSockBuf_Fill, remote host closed connection.
[quick start of Digital IC Verification] 24. AHB sramc of SystemVerilog project practice (4) (AHB continues to deepen)
Getting started with webgl (4)
[quick start for Digital IC Validation] 26. Ahb - sramc (6) for system verilog project practice (Basic Points of APB Protocol)
The difference between full-time graduate students and part-time graduate students!
微信小程序 01
Connecting FTP server tutorial
【Markdown语法高级】让你的博客更精彩(四:设置字体样式以及颜色对照表)
写一篇万字长文《CAS自旋锁》送杰伦的新专辑登顶热榜
【服务器数据恢复】戴尔某型号服务器raid故障的数据恢复案例
TypeScript 发布 4.8 beta 版本
Matlab experience summary
[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering
webgl_ Graphic transformation (rotation, translation, zoom)
What is data leakage
[quick start of Digital IC Verification] 22. Ahb-sramc of SystemVerilog project practice (2) (Introduction to AMBA bus)
Guangzhou Development Zone enables geographical indication products to help rural revitalization
【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
【目标检测】YOLOv5跑通VOC2007数据集
最安全的证券交易app都有哪些