当前位置:网站首页>Async and await
Async and await
2022-07-07 15:41:00 【When can Xiaobai advance to success】
1、async and Generator The relationship between
async yes Generator Grammatical sugar of function ( Grammatical sugar : A grammar added to a computer language , This grammar has no effect on the function of language , But it's easier for programmers to use . Generally speaking, the use of syntactic sugar can increase the readability of programs , So as to reduce the chance of program code error .).
Case a : Read two files
var fs = require('fs');
var readFile = function(fileName)
{
return new Promise(function(resolve,reject){
fs.readFile(fileName,function(error,data){
if(error)
{
return reject(error);
}
resolve(data);
});
});
}
var gen = function*(){
var f1= yield readFile('./hello.txt');
var f2= yield readFile('./world.txt');
}
var hw = gen();
hw.next().value.then((data)=>{console.log("22 success:"+data)},(error)=>{console.log("failed:"+error)});
hw.next().value.then((data)=>{console.log("22 success:"+data)},(error)=>{console.log("failed:"+error)});
console.log("333"+hw.next().value);take Generator The function is changed to async Form of function :
var gen2 = async function (){
var f1= await readFile('./hello.txt');
var f2= await readFile('./world.txt');
}async The function will be Generator Asterisk of function (*) Replace with async, take yield Replace with await, That's it .
2、async Function pair Generator Function improvements
(1) Built in actuator
async The execution of function is exactly the same as that of ordinary function , Just one line .
gen2();The code above calls gen2() function , Then it will automatically execute , Output the final result . It's not like it at all Generator Function needs to call next Method or use co Module can execute and get the final result .
(2) Better semantics
async and await Compared to asterisks and yield, The meaning is clearer .async Indicates that there is an asynchronous operation in the function ,await Indicates that the following expression needs to wait for the result .
(3) Wider applicability
co Module conventions ,yield The order can only be followed by Thunk Function or Promise object , and async Functional await Command behind , It can be Promise Value of object and original type ( The number , String and Boolean , But this is equivalent to synchronous operation ).
(4) The return value is Promise
async The return value of the function is Promise object , This is more than Generator The return value of the function is Iterator Objects are much more convenient . It can be used then Method to specify the next action .
summary :async Function can be regarded as one wrapped by multiple asynchronous operations Promise object , and await Command is internal then Grammar sugar of command .
3、 usage
(1)async Back to Promise object
var fs = require('fs');
var readFile = function(fileName)
{
return new Promise(function(resolve,reject){
fs.readFile(fileName,function(error,data){
if(error)
{
return reject(error);
}
resolve(data);
});
});
}
var gen2 = async function (){
var f1= await readFile('./hello.txt');
var f2= await readFile('./world.txt');
console.log(f1.toString());
console.log("f2:"+f2);
return "run end";//async The return value will become then Method callback function parameters
}
var hw = gen2();
hw.then((data)=>{console.log("22 success:"+data)},(error)=>{console.log("failed:"+error)});Running results :

async Internal function return The value returned by the statement , It's going to be then Method callback function parameters .
(2) False capture
var gen2 = async function (){
var f1= await readFile('./hello.txt');
var f2= await readFile('./world.txt');
console.log(f1.toString());
console.log("f2:"+f2);
throw new Error("Error!!!");
}
var hw = gen2();
hw.then((data)=>{console.log("22 success:"+data)},(error)=>{console.log("failed:"+error)});Running results :

async An error thrown inside a function results in a return Promise The object becomes reject state . The error object thrown will be catch Method callback received .
4、Promise The state of the object changes
async Function return Promise The object has to wait until it's internally owned await After the order Promise After the object is executed, the state will change , Unless you meet return Statement or throw error . namely : Only async The asynchronous operation inside the function is finished , Will execute then Callback function specified by method .
5、await command
Under normal circumstances ,await The command is followed by a Promise object . If not , Will be turned into an immediate resolve Of Promise object .
await After the order Promise If the object becomes reject state , be reject The parameters of will be catch Method's callback function received .
async function f(){
await Promise.reject('There is an error!!!');
}
f()
.then(v=>console.log(v))
.catch(e=>console.log(e));Running results :
![]()
In the above code ,await There is no return, however reject The parameters of the method are still passed in catch Callback function for method .
As long as a await After statement Promise Turn into reject, So the whole async Functions are interrupted .
Sometimes , We hope that even if the previous asynchronous operation fails , Do not interrupt the subsequent asynchronous operation , At this time, you can put the first await Put it in try...catch Inside the structure , So whether or not the asynchronous operation succeeds , the second await It will be carried out .
async function f(){
try{
await Promise.reject("EEEE ERROR");
}catch(e){
console.log(e);
}
return await Promise.resolve('run end');
}
f()
.then(v=>console.log(v));Running results :

边栏推荐
- TypeScript 发布 4.8 beta 版本
- 2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
- 【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
- Using eating in cocos Creator
- [quick start of Digital IC Verification] 29. Ahb-sramc (9) (ahb-sramc svtb overview) of SystemVerilog project practice
- 【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)
- 2022 all open source enterprise card issuing network repair short website and other bugs_ 2022 enterprise level multi merchant card issuing platform source code
- webgl_ Enter the three-dimensional world (2)
- 【數據挖掘】視覺模式挖掘:Hog特征+餘弦相似度/k-means聚類
- postman生成时间戳,未来时间戳
猜你喜欢
Configure mongodb database in window environment

Monthly observation of internet medical field in May 2022
![[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering](/img/a4/7320f5d266308f6003cc27964e49f3.png)
[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering

【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)

Unity之ASE实现全屏风沙效果

Unity之ASE实现卡通火焰

Tkinter after how to refresh data and cancel refreshing

【数字IC验证快速入门】25、SystemVerilog项目实践之AHB-SRAMC(5)(AHB 重点回顾,要点提炼)
![[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)](/img/7e/188e57ee026200478a6f61eb507c92.png)
[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)
Implementation of crawling web pages and saving them to MySQL using the scrapy framework
随机推荐
[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering
Vertex shader to slice shader procedure, varying variable
[make a boat diary] [shapr3d STL format to gcode]
2022年5月互联网医疗领域月度观察
什么是数据泄露
简述keepalived工作原理
Basic knowledge sorting of mongodb database
【兰州大学】考研初试复试资料分享
Unity's ASE realizes cartoon flame
Pat grade a 1103 integer factorizatio
[机缘参悟-40]:方向、规则、选择、努力、公平、认知、能力、行动,读3GPP 6G白皮书的五层感悟
Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
jacoco代码覆盖率
摘抄的只言片语
The download button and debug button in keil are grayed out
一个需求温习到的所有知识,h5的表单被键盘遮挡,事件代理,事件委托
Mathematical modeling -- what is mathematical modeling
[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)
[target detection] yolov5 Runtong voc2007 data set
【跟着江科大学Stm32】STM32F103C8T6_PWM控制直流电机_代码