当前位置:网站首页>Elegant asynchronous programming version answer async and await parsing
Elegant asynchronous programming version answer async and await parsing
2022-06-23 21:11:00 【henu_ Newxc03】
Catalog
async The advantages of functions
How do you use it? async function
async+await The basic structure
What is? aysnc and await
async Function is Generator Grammatical sugar of function .
use Generator function , Read two files in turn .
var fs = require('fs');
var readFile = function (fileName){
return new Promise(function (resolve, reject){
fs.readFile(fileName, function(error, data){
if (error) reject(error);
resolve(data);
});
});
};
var gen = function* (){
var f1 = yield readFile('/etc/fstab');
var f2 = yield readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};It's written in async function , That's what it looks like .
var asyncReadFile = async function (){
var f1 = await readFile('/etc/fstab');
var f2 = await readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};A comparison will reveal ,async The function will be Generator Asterisk of function (*) Replace with async, take yield Replace with await, That's it .
Why use async
To make our asynchronous code , More like synchronized code
aysnc Function solves what
stay async/await Before , We have three ways to write asynchronous code
- Nested callbacks
- With Promise Main chain callback
- Use Generators
however , None of the three is elegant enough to write ,ES7 Made optimization and improvement ,async/await emerge as the times require ,async/await Comparison Promise object then Nesting of functions , And Generator The implementation is tedious ( Need help co To automatically execute , Otherwise, you have to call it manually next() ), Async/Await It makes it easy for you to write synchronous code with asynchronous mechanism , More concise , Logic is clearer .
async The advantages of functions
async Function pair Generator Function improvements , This is reflected in the following three points .
(1) Built in actuator . Generator Function execution must depend on the actuator , That's why co function library , and async Function with actuator . in other words ,async Execution of a function , As like as two peas , Just one line .
var result = asyncReadFile();
(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 Function library conventions ,yield The order can only be followed by Thunk Function or Promise object , and async Functional await Command behind , Can follow Promise Value of object and original type ( The number 、 String and Boolean , But this is equivalent to synchronous operation ).
How do you use it? async function
async Function syntax
- Automatically convert regular functions to Promise, The return value is also a Promise object
- Only async The asynchronous operation inside the function is finished , Will execute then Callback function specified by method
- Asynchronous functions can be used internally await
async function name([param[, param[, ... param]]]) { statements }
name: The name of the function .
param: The name of the parameter to be passed to the function
statements: Function body statement .
Return value : Back to Promise The object will be async function Parse the return value of , Or reject the exception thrown by the function .
await grammar
- await Put in Promise Before you call ,await Force the following code to wait , until Promise object resolve, obtain resolve The value of await The result of an expression
- await Only in async Function internal use , If it is used in ordinary functions, it will report an error
[return_value] = await expression; expression: One Promise Object or any value to wait . Return value : return Promise The result of object processing . If it's not Promise object , Returns the value itself .
Error handling
stay async In the function , Whether it's Promise reject Data or logic error , Will be swallowed up silently , So it's better to await Put in try{}catch{} in ,catch Can capture Promise object rejected Data or exceptions thrown
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {reject('error')}, ms); //reject Simulation error , return error
});
}
async function asyncPrint(ms) {
try {
console.log('start');
await timeout(ms); // An error is returned here
console.log('end'); // So this code will not be executed
} catch(err) {
console.log(err); // Errors are caught here error
}
}
asyncPrint(1000);If not try/catch Words , You can also handle errors like this ( because async Function returns a promise)
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {reject('error')}, ms); //reject Simulation error , return error
});
}
async function asyncPrint(ms) {
console.log('start');
await timeout(ms)
console.log('end'); // This code will not be executed
}
asyncPrint(1000).catch(err => {
console.log(err); // Errors are caught here
});If you don't want the error to interrupt the execution of the following code , It can intercept and retain errors in advance , Like the following
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('error')
}, ms); //reject Simulation error , return error
});
}
async function asyncPrint(ms) {
console.log('start');
await timeout(ms).catch(err => { // Pay attention to catch
console.log(err)
})
console.log('end'); // This code will be executed
}
asyncPrint(1000);async+await The basic structure
function func(a, b) {
return a + b
}
let ret = func(10, 30);
let ret1 = func(50, 320);
let ret2 = func(1560, 30);
let ret3 = func(10, 3560);
console.log(ret + ret1 + ret2 + ret3);If Promise Objects can also have corresponding ways to receive , Write similar :
let data1 = await readfilePromise; // Get the successful data directly
async The final format of is as follows :
async function func() {
let data1 = await promise object 1;
let data2 = await promise object 2;
let data3 = await promise object 3;
}
// It's equivalent to making asynchronous function objects 1 After execution , Then execute the asynchronous function object 2, Then execute the asynchronous function object 3matters needing attention
- If await Only one basic data type is written later , Wrap this basic data type , Pack it as a Promise object
async function func() {
let data1 = await 123;
//1. await Only one basic data type is written later Wrap this basic data type , Pack it as a Promise object
// namely data1 amount to : new Promise((resolve,reject)=>{resolve(123)})
console.log("data1:", data1); //data1: 123
return data1
// return await data1
}
let a = func();
a.then((data)=>{
console.log(data); //123 Received the above return value Promise Object execution results
});- If await There's a Promise, Will be able to resolve The value of the return
- async Inside the function await It's asynchronous , Not synchronization
async function func() {
console.log("start-------");
let data1 = await readFile(filePath1, "utf-8");
console.log("end-----------");
let data2 = await readFile(filePath2, "utf-8");
let data3 = await readFile(filePath3, "utf-8");
console.log(data1+data2+data3);
}
console.log("start");
func();
console.log("end");
// The output results are as follows :
//start
//start-------
//end
//end-----------
边栏推荐
- Advantages of token mechanism over cookie mechanism
- 100 lines of code, using pyGame to make a snake game!
- Process injection
- Customize view to imitate today's headlines and like animation!
- Where should DNS start? I -- from the failure of Facebook
- How to process the text of a picture into a table? Can the text in the picture be transferred to the document?
- Easyplayer player error 502 bad gateway problem analysis
- JS chain call
- [JS reverse hundred examples] anti climbing training platform for netizens question 6: JS encryption, environment simulation detection
- How to dispose of the words on the picture? How do I add text to a picture?
猜你喜欢
随机推荐
Does the fortress machine need a server? Understand the architectural relationship between fortress machine and server
[development skills] how to add "live broadcast" status display bar on easynvr platform
Summary of multiple methods for obtaining the last element of JS array
How to make a material identification sheet
Use Tencent cloud lightweight application server to build an unlimited network disk -zpan building tutorial
打新债到底是用什么软件比较安全?打新债平台有哪些
RI Gai series: push of STD container_ Why is back slower than []
How to solve the problem of large traffic audio audit? What are the common approval methods?
Machine learning related
Global and Chinese market of microphone racks 2022-2028: Research Report on technology, participants, trends, market size and share
JS naming conventions
How to build a personal cloud game server? How many games can the cloud game platform install?
Making CSR file for face core
. Net cloud native architect training camp (rgca four step architecture method) -- learning notes
How do I view the server when I log in to the fortress machine? Operation guide for novice
Row height, (top line, middle line, baseline, bottom line), vertical align
手续费佣金低的券商,华泰证券网上开户安全吗
Cloudbase init considerations
[hot sales at the beginning of the year] | the first special offer of popular cloud products is second to none, and the first year of 1-core 2G cloud server is 38 yuan!
网上证券开户安全还是去营业部安全



