当前位置:网站首页>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 .
边栏推荐
- Actually changed from 408 to self proposition! 211 North China Electric Power University (Beijing)
- Qu'est - ce qu'une violation de données
- There is a cow, which gives birth to a heifer at the beginning of each year. Each heifer has a heifer at the beginning of each year since the fourth year. Please program how many cows are there in the
- [quick start of Digital IC Verification] 19. Basic grammar of SystemVerilog learning 6 (thread internal communication... Including practical exercises)
- OpenGL common functions
- HW primary flow monitoring, what should we do
- 全日制研究生和非全日制研究生的区别!
- Create lib Library in keil and use lib Library
- 【OBS】RTMPSockBuf_Fill, remote host closed connection.
- Unity之ASE实现卡通火焰
猜你喜欢

webgl_ Enter the three-dimensional world (1)

Mathematical modeling -- what is mathematical modeling

Steps to create P8 certificate and warehousing account

从 1.5 开始搭建一个微服务框架链路追踪 traceId

众昂矿业:萤石继续引领新能源市场增长
![[quick start of Digital IC Verification] 24. AHB sramc of SystemVerilog project practice (4) (AHB continues to deepen)](/img/cf/45775b712f60869186a25d3657ee1b.png)
[quick start of Digital IC Verification] 24. AHB sramc of SystemVerilog project practice (4) (AHB continues to deepen)

HPDC smart base Talent Development Summit essay

Getting started with webgl (4)

Cocos creator collision and collision callback do not take effect

Yunxiaoduo software internal test distribution test platform description document
随机推荐
[server data recovery] data recovery case of raid failure of a Dell server
[Lanzhou University] information sharing of postgraduate entrance examination and re examination
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
Cocos uses custom material to display problems
微信小程序 01
The download button and debug button in keil are grayed out
【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)
什么是数据泄露
How to build your own super signature system (yunxiaoduo)?
【搞船日记】【Shapr3D的STL格式转Gcode】
[quick start for Digital IC Validation] 26. Ahb - sramc (6) for system verilog project practice (Basic Points of APB Protocol)
【深度学习】图像超分实验:SRCNN/FSRCNN
[quick start of Digital IC Verification] 20. Basic grammar of SystemVerilog learning 7 (coverage driven... Including practical exercises)
Ida Pro reverse tool finds the IP and port of the socket server
[quick start of Digital IC Verification] 19. Basic grammar of SystemVerilog learning 6 (thread internal communication... Including practical exercises)
Android -- jetpack: the difference between livedata setValue and postvalue
【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)
webgl_ Graphic transformation (rotation, translation, zoom)
[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering
[quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)