当前位置:网站首页>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 .
边栏推荐
- How to release NFT in batches in opensea (rinkeby test network)
- 如何在opensea批量发布NFT(Rinkeby测试网)
- [deep learning] image hyperspectral experiment: srcnn/fsrcnn
- Share the technical details of super signature system construction
- [make a boat diary] [shapr3d STL format to gcode]
- 2. Heap sort "hard to understand sort"
- [server data recovery] data recovery case of raid failure of a Dell server
- Zhongang Mining: Fluorite continues to lead the growth of new energy market
- 有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
- 【数字IC验证快速入门】23、SystemVerilog项目实践之AHB-SRAMC(3)(AHB协议基本要点)
猜你喜欢
2022年5月互联网医疗领域月度观察
【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)
Unity's ASE achieves full screen sand blowing effect
Introduction of mongod management database method
Yunxiaoduo software internal test distribution test platform description document
MongoD管理数据库的方法介绍
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
Ctfshow, information collection: web13
【目标检测】YOLOv5跑通VOC2007数据集
webgl_ Enter the three-dimensional world (1)
随机推荐
Getting started with webgl (3)
Create lib Library in keil and use lib Library
Vertex shader to slice shader procedure, varying variable
Basic knowledge sorting of mongodb database
【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)
Matlab experience summary
【原创】一切不谈考核的管理都是扯淡!
[quick start of Digital IC Verification] 23. AHB sramc of SystemVerilog project practice (3) (basic points of AHB protocol)
How to release NFT in batches in opensea (rinkeby test network)
2. Heap sort "hard to understand sort"
Use cpolar to build a business website (2)
Pit avoidance: description of null values in in and not in SQL
简述keepalived工作原理
MongoD管理数据库的方法介绍
How to understand that binary complement represents negative numbers
[Lanzhou University] information sharing of postgraduate entrance examination and re examination
Webgl texture
How to create Apple Developer personal account P8 certificate
STM32F103C8T6 PWM驱动舵机(SG90)
MongoDB数据库基础知识整理