DEV Community

Cover image for Async & await explained in short
Rahul
Rahul

Posted on • Updated on

Async & await explained in short

Async & await basically just syntactic sugar on top of promises. Here is my latest post and very short and amazing explanation of Async and await.


If you use the async keyword before the function definition, you can then use await within the function. Await gives you the power to pause the function in a non-blocking way until the promise is settled.

If the promise fulfils, you get the value back. If not, the rejected value is thrown. Here is a perfect example for you below:-

async function fetchUsers( endpoint ) {
  const res = await fetch( endpoint );
  const data = await res.json();
  const usernames = data.map( user => user.username);
  console.log(usernames);
}

fetchUsers( 'https://jsonplaceholder.typicode.com/users'); 
/* 
["Bret", "Antonette", "Samantha", "Karianne", "Kamren", "Leopoldo_Corkery", "Elwyn.Skiles", "Maxime_Nienow", "Delphine", "Moriah.Stanton"]
*/
Enter fullscreen mode Exit fullscreen mode

First, the given endpoint is fetched. At this point, the function pauses until the fetch Promise is fulfilled.

After that, the response is read and parsed as JSON. Because we await that too, JSON() is a Promise aswel, we pause the function again until it is fulfilled.

When that's all done we can use the data retrieved and for example map it and log it to the console.

What is one of the awaits gets rejected?

=> We can add a catch() to every single await because they're just normal Promises!

With the catches added to the awaits, our function will look like the example below.

async function fetchUsers( endpoint ) {
  const res = await fetch( endpoint ).catch(e => console.error(e.message));
  const data = await res.json().catch(e => console.error(e.message);
  const usernames = data.map( user => user.username);
  console.log(usernames);
}
Enter fullscreen mode Exit fullscreen mode


Read More :-

Help Needed Plz

Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.


1.png


This was something short I wanted to share!

⚡Happy Coding.

Top comments (4)

Collapse
 
lico profile image
SeongKuk Han

I didn't know that can use the 'catch' to an await function.
I've been used only try-catch block for catching errors. and I've just known that only works.
Thanks for your post :)

Collapse
 
hnicolas profile image
Nicolas Hervé

You can use catch on a promise and it will return another promise.
You can use await on a promise to wait for the result.
So everything is ok with the example, even if with the await keyword you can use a try/catch block to catch the error rejected by a promise.

Collapse
 
lico profile image
SeongKuk Han

Thank you :DD

Collapse
 
rahxuls profile image
Rahul

Welcome!