Async /await is an asynchronous solution. Compared with other asynchronous solutions, async/await syntax is relatively simple to use and has no big difference with synchronous methods.

Use the async/await

function promiseFn () {
    return new Promise((resolve, reject) = > {
        resolve(1);
    });
}

async function asyncFn() {
    const num = await promiseFn();
    console.log(num);  
}

asyncFn();  / / 1
Copy the code

Resolve () an implicit call is made to promise.resolve () to ensure that a Promise is returned if nothing behind await returns a Promise.

function notPromiseFn () {
    return 1;
}

async function asyncFn () {
    const num = await notPromiseFn();
    console.log(num);
}
async function asyncFn2 () {
    const num = await Awesome!;
    console.log(num);   
}

asyncFn(); / / 1

asyncFn2(); / / 666
Copy the code

So, we can use async/await, regardless of the type returned after await. After all, the purpose of async/await is to implement asynchronous operations in synchronous mode. It is a bit superfluous to use async/await in synchronous code.

Exception handling

Exception handling is a problem that must be considered in writing code, so exception handling must also be done in async/await.

function errorPromiseFn(type) {
    return new Promise((resolve, reject) = > {
        if (type === 'error') {
            throw new Error('Error');
        }
        resolve(404);
    });
}

async function errorFn() {
    try {
        const res = await errorPromiseFn('error');
        console.log(res);
    } catch (err) {
        console.error(err);
    }
}

errorFn('error'); // Exceptions are captured
Copy the code

Serial and parallel

As we know, synchronous code is executed serially. But sometimes, we don’t want to do it all sequentially. For example, when you need to request data from multiple interfaces that are not interdependent, the best solution is to execute in parallel.

function getData1() {
    return new Promise((resolve, reject) = > {
        fetch(url).then(res= > resolve(res));
    });
}

function getData2(url) {
    return new Promise((resolve, reject) = > {
        fetch(url).then(res= > resolve(res));
    });
}

async serialGetAllData() {
    // Create a promise and wait for the result to be processed
    const data1 = await getData1();
    // Wait for the previous processing result to complete, then create a promise and process the result
    const data2 = await getData2();
    return {data1, data2};
}

serialGetAllData();
Copy the code

SerialGetAllData does not need to wait until the data1 request is complete. So, we want them to be synchronized.

Promise.all implements asynchronous parallelism

Promise.all supports multiple Promise requests in parallel. So, in async/await, we can implement parallel requests with promise.all.

async parallelGetAllData() {
    const [data1, data2] = await Promise.all([
        getData1(),
        getData2()
    ]);
    return {data1, data2};
}

parallelGetAllData();
Copy the code

Create a Promise and then use await

In addition to the promise.all method, there is another way to implement parallel operations: create a Promise and then use await.

async parallelGetAllData() {
    // Create multiple Promise instances
    const promise1 = getData1();
    const promise2 = getData2();
    // Wait for multiple promises at the same time,
    Promise1 takes 3 seconds, promise2 takes 2 seconds,
    // As both promise1 and promise2 request at the same time,
    // Data1 and data2 can be obtained in 3 seconds
    const data1 = await promise1;
    const data2 = await promise2;
    return {data1, data2};
}
Copy the code

Use async/await in the body of the loop

Sometimes we need to do asynchronous operations in the body of the loop

async function serialLoop() {
    let promises = [getData1, getData2];
    for (let promise of promises) {
       const data = await promise();
       console.log(data);
    }
}

serialLoop();
Copy the code

Obviously, the above code is executed sequentially, so if getData1 takes 3 seconds and getData2 takes 2 seconds, the whole process will take 5 seconds to complete.

In the previous section, we learned that async/await can be modified to execute in parallel

async function parallelLoop() {
    let promises = [getData1(), getData2()];
    for (let promise of promises) {
        const data = await promise;
        console.log(data);
    }
}
parallelLoop();
Copy the code

This way, it only takes 3 seconds to execute.