[This is the 10th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.]

Yesterday’s article “Async and await in JavaScript” briefly explained how to use them. So how async and await work and how to use async and await correctly.

What are async and await?

In short, they are syntax candies nested with promises. Here’s an example:

async function helloAsync() {
    const result = await new Promise((resolve) =>
        setTimeout(() => resolve("Hello"))
    );
    console.log(result); // Hello
}

helloAsync();
Copy the code

Running the above code, the function will print “Hello” with obvious results, where the await will block the main thread until the promise is processed.

async

The async function enables us to write promise-based code as if it were synchronous, but without blocking the thread of execution. Running asynchronously through the event loop, the async function will always return a value. Use async to simply return apromise. If an apromise is not returned, it is automatically wrapped in apromise with its value resolve.

await

The await operator is used to wait for promises and can only be used inside async blocks. The keyword await causes JavaScript to wait until the PROMISE returns the result.

Note that it just makes the Async function block wait, not the entire program execute. You cannot use the await keyword in regular functions.

Guess the output of the code snippet below

async function helloAsync() { const result = await new Promise((resolve) => setTimeout(() => resolve("Hello")) ); return result; } let asyncResult = helloAsync(); Console. log("helloAsync returns value: "+ json.stringify (asyncResult));Copy the code

The value of asyncResult is {}. From the output, the variable asyncResult has a value of {}.

Why is that?

Because the asynchronous function always returns a promise, rather than resolving the promise in the example above, we try to extract value from it.

How to solve it?

Since the async function returned a promise object in the above code snippet, you can use the.then method to get the processing result of the async function. The following code normally prints the result of async function execution.

async function helloAsync() { const result = await new Promise((resolve) => setTimeout(() => resolve("Hello")) ); return result; } helloAsync().then((data) => {console.log("helloAsync return value: "+ json.ify (data)); });Copy the code

A better way

The main reason to use async and await is to avoid the use of promise chains or.then expressions, so you can use async and await themselves to resolve promises instead of.then. The following code is recommended:

async function helloAsync() { const result = await new Promise((resolve) => setTimeout(() => resolve("Hello")) ); return result; } async function testHelloAsync() { const output = await helloAsync(); Console. log("helloAsync return value: "+ json.stringify (output)); } testHelloAsync();Copy the code

conclusion

In real projects, there is no good or bad choice between Promises and Async/Await, depending on the developer. I personally prefer Promises right now.