This article mainly uses a lot of examples to explain why async/await should be used instead of promise.


01 background

Async function defines an asynchronous function that returns an AsyncFunction object. An asynchronous function is a function that executes asynchronously through an event loop and returns its result with an implicit Promise. If you use async/await in your code, you will find that the syntax and structure is more like a standard synchronization function.

The async/await introduced in ES7 is a major improvement over asynchronous JavaScript programming, providing the ability to access resources asynchronously using synchronous code without blocking the main thread.

The Promise object is used to represent the final state (completion or failure) of an asynchronous operation, as well as the result value of that asynchronous operation.

02 example

Promise,

As opposed to applying async/await,

This example is fine, but note that the promise must catch an exception (i.e.,.catch). If it does not catch an exception, an error will be received in the browser’s onError function

promise error

Obviously, async asynchronous functions look like synchronous mode, so it is more convenient to catch exceptions and debug breakpoints.

Promises can be a bit complicated if you want to execute many asynchronous functions at the same time, or if you want to execute them simultaneously (in parallel or serial).

It is much more elegant to use async/await,

The serial asynchronous function example above is a bit more complicated if it was promise with two layers of nesting, not to mention three and four layers of serial code.

But the async/await writing is the same, it looks very friendly, and the code is readable and maintainable better than promise.

What if it’s a parallel asynchronous function? Promise all

This is the most time efficient way to wait until all requests come back together. Is there a similar way to async/await? It’s actually possible.

1. Async/await can also be used promise.all

Therefore, if there are multiple parallel requests, async + promise.all can also be combined to handle them.

2. Things you may not know about async/await concurrency

If we don’t need to wait for all concurrent asynchronous functions or requests to come back, we can.

If async/await multiple serial, then this is it,

So why is that? Since the forEach pass is a callback function, you can understand that arr. ForEach (callback) is

So if the callback of a forEach is an asynchronous function, then the asynchronous function is concurrent.

Welcome to the public number: front-end full stack technology, continue to update the latest articles.