All About Async/Await an ES7 feature


Topics to be covered:

How to fetch multiple asynchronous data sequentially using async/await (i.e. One after the other)
How to fetch multiple asynchronous data in parallel (i.e. All API’s triggered at same instance)
How to handle promise rejections using async/await.

prior to the above concepts, first let’s get an idea on how async works with a function.

A function consisting ‘async’ keyword returns a promise. Later the promise can be resolved using ‘.then’.

Async function returns Promise

To reject we use ‘throw’ keyword. Hence, we observe that promise status returned on function call is ‘rejected’.

Reject a promise using throw keyword
How to handle promise rejections using async/await.

Once promise is rejected, they should be handled. Rejections are handled using ‘try and catch’. Add async logic in ‘try’ block and logic to handle and display respective error in ‘catch’ block.

handle rejections using catch
How to fetch multiple asynchronous data sequentially using async/await (i.e. One after the other)

If we want to retrieve list of species from star wars api : ‘https://swapi.co/api/people/1’ and then from the response make an API call to retrieve first species average life span we have to make sequential calls as below (using async await).

The average life span of species1 is ‘120'

Below is the picture depicting the waterfall of network calls

fetch people/1 and on finishing trigger species/1
How to fetch multiple asynchronous data in parallel (i.e. All API’s triggered at same instance)

In few scenarios’s the series of api to be fetched are independant. We can trigger the async calls at same instance. i.e. in Parallel.

To make multiple API call’s in parallel using async await, fetch the data individually and later use ‘await’ as below:

Add await keyword for Data1 and Data 2 post fetch statements

Using the above behaviour the api calls are triggered in parallel. Below is the diagram of network API call which confirms it.

people/1 and people/2 async fetch calls are triggered at same instance

There is an other way, through which async fetch api calls can be triggered in parallel. i.e. using Promise.all()

people/1 people/2 and people/3 are three async api’s that are triggered in parallel

Below is the network waterfall diagram for fetching multiple api’s like people/1, people/2 and people/3 at single instance.

1/, 2/ and 3/ are triggered at same instance.

Please clap if the information provided was helpful. Thanks.