当前位置:网站首页>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 .
边栏推荐
- MySQL bit type resolution
- How to create Apple Developer personal account P8 certificate
- 【目标检测】YOLOv5跑通VOC2007数据集
- 2.Golang基础知识
- Connecting FTP server tutorial
- Mathematical modeling -- what is mathematical modeling
- What is Base64?
- 众昂矿业:萤石继续引领新能源市场增长
- [make a boat diary] [shapr3d STL format to gcode]
- Cocos uses custom material to display problems
猜你喜欢
[机缘参悟-40]:方向、规则、选择、努力、公平、认知、能力、行动,读3GPP 6G白皮书的五层感悟
Yunxiaoduo software internal test distribution test platform description document
Briefly describe the working principle of kept
[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering
2. 堆排序『较难理解的排序』
2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
Introduction of mongod management database method
写一篇万字长文《CAS自旋锁》送杰伦的新专辑登顶热榜
【数字IC验证快速入门】26、SystemVerilog项目实践之AHB-SRAMC(6)(APB协议基本要点)
HW primary flow monitoring, what should we do
随机推荐
使用cpolar建立一个商业网站(2)
Nacos一致性协议 CP/AP/JRaft/Distro协议
居然从408改考自命题!211华北电力大学(北京)
PAT 甲级 1103 Integer Factorizatio
【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)
【OBS】RTMPSockBuf_ Fill, remote host closed connection.
TypeScript 发布 4.8 beta 版本
【目标检测】YOLOv5跑通VOC2007数据集
Points for attention in porting gd32 F4 series programs to gd32 F3 series
Zhongang Mining: Fluorite continues to lead the growth of new energy market
15. Using the text editing tool VIM
一大波开源小抄来袭
Runnable是否可以中断
[quick start of Digital IC Verification] 29. Ahb-sramc (9) (ahb-sramc svtb overview) of SystemVerilog project practice
Jacobo code coverage
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
【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
MongoDB数据库基础知识整理
Steps to create P8 certificate and warehousing account
HPDC smart base Talent Development Summit essay