Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using async/await?

I'm reading several articles and seeing some videos about how to use async/await in JavaScript and seems that the only reason is to transform asynchronous code in synchronous code (and make code more readable but this is not intended to be discussed in this question).

So, I would like to understand if there are more reasons on using these statements because, in my understanding, if we have Promises to make async calls and improve the performance of our code, why we want to convert it again to synchronous code?

like image 349
jaloplo Avatar asked Dec 13 '22 11:12

jaloplo


2 Answers

It can be considered to be not actually synchronous. When you await something that is async, it gets added to a microtask queue. It does not run on the main thread, meaning other things can occur (click events, rendering, etc.)

Here is a fantastic talk that can explain it in further detail https://www.youtube.com/watch?v=cCOL7MC4Pl0

await/async are often referred to as syntactic sugar, and let us wait for something (e.g. an API call), giving us the illusion that it is synchronous.

like image 60
Toby Mellor Avatar answered Dec 24 '22 03:12

Toby Mellor


I think async await increases the readability of the code. In some promise-callback uses, you can find yourself in a very long chain, which can be called a callback pit. it is up to you to consider whether to use async-await.

like image 38
Hayreddin Tüzel Avatar answered Dec 24 '22 01:12

Hayreddin Tüzel