Currently async/await has been standardized and we need to put the learning process on the agenda as soon as possible. Async is used as a keyword in front of a function to indicate that it is an asynchronous function, because async means asynchronous, and asynchronous function means that the execution of the function does not block the execution of the following code. Write an async function:

Async function timeout() {return 'hello world'; }Copy the code

Async: async: async: async: async: async: async: async Async function is also a function, and we use it as we normally use it. We call it with parentheses. To show that it does not block the execution of the code following it, we add console.log after async function call.

async function timeout() { return 'hello world' } timeout(); Console. log(' I'll do it first, though I'll do it later ');Copy the code

Async timeout is called but has no output. Should it return ‘Hello world’? Change the timeout() statement above to console.log(timeout()).

async function timeout() { return 'hello world' } console.log(timeout()); Console. log(' I'll do it first, though I'll do it later ');Copy the code

Let’s move on to the console

The async function returns a Promise object. If we want to get the promise, we should use the then method to continue modifying the code.

async function timeout() { return 'hello world' } timeout().then(result => { console.log(result); }) console.log(' I'll do it first, though later ');Copy the code

See the console

We get ‘Hello World’, and the execution of timeout does not block the execution of the following code, as we just said. At this point, you may notice that the Promise in the console has an resolved, which is the implementation principle inside the Async function. If an async function returns a value, the promise.solve () method is called internally to return it as a Promise object, but what if the timeout function throws an error internally? The promise.reject () call returns a Promise object, in which case modify the timeout function.

async function timeout(flag) { if (flag) { return 'hello world' } else { throw 'my god, Failure '}} console.log(timeout(true)) // call promise.resolve () to return a Promise object. console.log(timeout(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.

timeout(false).catch(err => {
    console.log(err)
})
Copy the code

‘async’ is almost done. Let’s consider the ‘await’ keyword. ‘await’ means to wait, so what is it waiting for and what is followed by it? You can put any expression after it, but we’re going to put an expression that returns a Promise object. Note that the await keyword can only be placed inside async functions.

Now let’s write a function that returns a Promise object that multiplies the number by 2 after 2s.

Function doubleAfter2seconds(num) {return new Promise(resolve, resolve) reject) => { setTimeout(() => { resolve(2 * num) }, 2000); })}Copy the code

Now write an async function so that you can use the await keyword. After await is an expression that returns a Promise object, so it can be followed by a call to the doubleAfter2seconds function.

async function testResult() {
    const result = await doubleAfter2seconds(30);
    console.log(result);
}
Copy the code

Now call the testResult function:

testResult();
Copy the code

I open the console, and after 2s, I get 60.

Now if we look at the code executing, we call testResult, and it says await, await, wait a minute, the code is paused here, it’s not going down, what is it waiting for? It waits for the subsequent Promise object to complete execution, then retrieves the promise resolve value and returns it. Once the return value is retrieved, it continues execution. In our code, after we encounter await, the code suspends execution until doubleAfter2seconds(30) completes, and the promise returned by doubleAfter2seconds(30) begins execution. After2seconds, the promise resolves, And returns the value 60, at which point await gets the return value 60, assigns the value to result, pauses and the code continues to execute the console.log statement.

We may not see the use of async/await in this one function, but what if we want to count 3 numbers and output the result?

async function testResult() {
    const first = await doubleAfter2seconds(30);
    const second = await doubleAfter2seconds(50);
    const third = await doubleAfter2seconds(30);
    console.log(first + second + third);
}
Copy the code

After six seconds, the console outputs 220, and we can see that writing asynchronous code is like writing synchronous code, no more callback hell. This is async/await to handle asynchrony.