async / await solves asynchronous problems

async / await is a solution proposed by ECMAScript7 to solve asynchronous problems. This is clearer and more convenient to use than ES6 promises.

usage:

  1. Add a asynckeyword in front of the function in JavaScript , then the return result of this function will become a Promise object.
  2. await must be placed in the async function
  3. Connect a function after await to wait for the execution of this function to complete. If this function returns a Promise, wait for the completion of the asynchronous result execution (resolve ()) in this function before continuing to execute; if it returns a non-Promise, then The code in the function returns after execution, regardless of whether there is an asynchronous result.

Example: async / await used with promise

const fs = require("fs");
const read = function(fileName){
    return new Promise((resolve,reject)=>{
        fs.readFile(fileName,(err,data)=>{
            if (err) {
                reject(err);
            } else{
                resolve(data);
            }
        });
    });
};
async function readByAsync(){
    let a1 = await read('1.txt');
    let a2 = await read('2.txt');
    let a3 = await read('3.txt');
    console.log(a1.toString());
    console.log(a2.toString());
    console.log(a3.toString());
}
readByAsync();

Note: When the Promise object after the await statement becomes the reject state, then the entire async function will be interrupted, and subsequent programs will not continue to execute, so you need to deal with it through try ... catch.

const fs = require("fs");
const read = function(fileName){
    return new Promise((resolve,reject)=>{
        fs.readFile(fileName,(err,data)=>{
            if (err) {
                reject(err);
            } else{
                resolve(data);
            }
        });
    });
};
async function readByAsync(){
    let a1;
    let a2;
    let a3;
    try{
        a1 = await read('1.txt');
        a2 = await read('2.txt');
        a3 = await read('3.txt');
    }catch(e){
        //TODO handle the exception
    }
    console.log(a1);
    console.log(a2);
    console.log(a3);
}
readByAsync();
Published 398 original articles · Liked 182 · Visits 370,000+

Guess you like

Origin blog.csdn.net/yexudengzhidao/article/details/105465862
Recommended