Simply put, they’re nested syntactic candy promises. Here’s one:

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

helloAsync();
Copy the code

Run the code above and the function will print “Hello”, with the obvious result that await will block the main thread until the promise processing is complete.

async

The async function enables us to write code based on promises as if it were synchronous, but without blocking the thread of execution. Run asynchronously through an event loop, async functions will always return a value. Using async simply returns apromise, and if apromise does not return, it is automatically wrapped in apromise with its value in resolve.

await

The await operator is used to wait for promises and can only be used within the async block. The keyword await causes JavaScript to wait until a promise returns a result.

Note that it only makes the async function block wait, not the whole 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 return value: "+ json.stringify (asyncResult));Copy the code

Based on the above code, you might think that the output “Hello”, right and wrong to see is true, copy the above code, the output is: asyncResult value: {}, from the output, the variable asyncResult value is {}.

Why is that?

Because asynchronous functions always return 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 returns a Promise object in the code snippet above, you can use the.then method to get the processing results 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.stringify (data)); });Copy the code

A better way

The main purpose of using async and await is to avoid using promise chains or.then expressions, so you can use async and await themselves to solve 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

Promises or Async/Await are no good or bad in real development projects. It depends on the developer. I personally prefer to use Async/Await at the moment.