The use of the async

Async is placed before a function as a keyword to indicate that the function is asynchronous, which means that the execution of the function does not block the execution of subsequent code

Below is an async function that can be called in parentheses.

    async function test() {
        return 'Hello World';
    }
    console.log(test());
Copy the code

Looking at the console, the function returns a Promise object, and we get Hello World without blocking the execution of subsequent code.

async function test() { return 'Hello World'; } test().then(res => { console.log(res); // Hello World }); Console. log(' execute first ');Copy the code

Notice that the Promise in the console above has an Resolved, which is the implementation principle inside the Async function. If an async function returns a value, the promise.resolve () method is called internally to return it as a Promise object. If an error is thrown internally, A call to promise.reject () returns a Promise object.

async function test(flag) { if (flag) { return 'Hello World'; } else { throw 'Oh my god'; } } console.log(test(true)); // Call promise.resolve () to return the Promise object. console.log(test(false)); // Call promise.reject () to return a Promise object.Copy the code

If a function throws an error internally, the Promise object has a catch method to catch it.

     test().catch(err => {
         console.log(err);
     });
Copy the code

Await the usage of the

Await means async/wait. This keyword can only be used in functions defined using async. Any async function will return a promise by default, and the value resolved by the promise will be the return value of the function, while async functions must wait until all the promise objects of the internal await command have finished executing before the state changes.

function getResult(num) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(num * 10); }, 2000); } ) } async function testResult() { let result = await getResult(2); console.log(result); } testResult(); // output 20 after 2sCopy the code

Code execution process: After calling testResult and hearing await, the code suspends execution, waits for getResult(2) to complete, and the promise returned by getResult(2) to execute. After 2s, the promise resolves. And returns 20, await gets the return value 20, assigns to result, pauses, and the code continues to execute the console.log statement.