jaloplo
jaloplo

Reputation: 951

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?

Upvotes: 5

Views: 3326

Answers (3)

Toby Mellor
Toby Mellor

Reputation: 8205

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.

Upvotes: 11

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

Sometimes you need multiple actions inside single functions, some of them may be asynchronous and some may be synchronous. Let's say you have following code with promises.

getUser().then(user => {
    getOrders({
        user: user
    }).then(orders => {
        console.log(orders)
    })
})

now what if you want orders to be fetched only if a condition is true, but let further code run as it is, then if you are using promises, you have to create a separate function and then call that function like this

function logOrders(orders) {
    console.log(orders)
}


getUser().then(user => {
    if (user.hasOrders) {
        getOrders({
            user: user
        }).then(logOrders)
    } else {
        logOrders([])
    }
})

but using async/await you can do it like this

(async () => {

    const user = await getUser();
    let orders = [];

    if (user.hasOrders) {
        orders = await getOrders({
            user: user
        })
    }

    console.log(orders)

})()

Upvotes: -1

Hayreddin Tüzel
Hayreddin Tüzel

Reputation: 949

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.

Upvotes: 2

Related Questions