当前位置:网站首页>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

What is? aysnc and await

Why use async

aysnc Function solves what

async The advantages of functions

How do you use it? async function

async Function syntax

await grammar

Error handling

async+await The basic structure

matters needing attention


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

  1. Nested callbacks
  2. With Promise Main chain callback
  3. 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 3

matters needing attention

  1. 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 
});
  1. If await There's a Promise, Will be able to resolve The value of the return
  2. 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-----------

原网站

版权声明
本文为[henu_ Newxc03]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112261502153953.html

随机推荐