当前位置:网站首页>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 deploy the super signature distribution platform system?
- Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
- Oracle控制文件丢失恢复归档模式方法
- Using eating in cocos Creator
- ./ Functions of configure, make and make install
- Nacos conformance protocol cp/ap/jraft/distro protocol
- Getting started with webgl (2)
- What is Base64?
- 2022年5月互联网医疗领域月度观察
猜你喜欢
Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
Vertex shader to slice shader procedure, varying variable
2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
[quick start of Digital IC Verification] 22. Ahb-sramc of SystemVerilog project practice (2) (Introduction to AMBA bus)
2022 all open source enterprise card issuing network repair short website and other bugs_ 2022 enterprise level multi merchant card issuing platform source code
How to create Apple Developer personal account P8 certificate
Write a ten thousand word long article "CAS spin lock" to send Jay's new album to the top of the hot list
有钱人买房就是不一样
微信小程序 01
The rebound problem of using Scrollview in cocos Creator
随机推荐
Nacos conformance protocol cp/ap/jraft/distro protocol
众昂矿业:萤石继续引领新能源市场增长
The significance of XOR in embedded C language
Runnable是否可以中断
Guangzhou Development Zone enables geographical indication products to help rural revitalization
[follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code
Excerpted words
[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering
15. Using the text editing tool VIM
OpenGL's distinction and understanding of VAO, VBO and EBO
2022年5月互联网医疗领域月度观察
Matlab experience summary
【數字IC驗證快速入門】20、SystemVerilog學習之基本語法7(覆蓋率驅動...內含實踐練習)
【目标检测】YOLOv5跑通VOC2007数据集
Streaming end, server end, player end
Spin animation of Cocos performance optimization
知否|两大风控最重要指标与客群好坏的关系分析
摘抄的只言片语
Configure mongodb database in window environment
Zhongang Mining: Fluorite continues to lead the growth of new energy market