admin管理员组

文章数量:1278820

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?

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?

Share Improve this question asked Jun 29, 2019 at 10:17 jaloplojaloplo 9512 gold badges12 silver badges32 bronze badges 15
  • 1 I believe it's nothing but syntactic sugar. Promises are really hard to understand pletely and many people never really get them fully right and good old nested callbacks don't scale nicely. – Álvaro González Commented Jun 29, 2019 at 10:23
  • 2 It's not synchronous code. It's code that's running sequentially and asynchronously but still following control structures. Nothing more nothing less. – Bergi Commented Jun 29, 2019 at 10:27
  • 1 Why do you think promises improve performance? They only make it simpler to deal with asynchronous results. – Bergi Commented Jun 29, 2019 at 10:28
  • 1 @jaloplo let count=0; function done() { console.log("callback", count); if (++count == 2) console.log("Both done"); } setTimeout(done, 1000); setTimeout(done, 1500); - the two timeouts happen concurrently. Or use the async.js library or so for these things. – Bergi Commented Jun 29, 2019 at 13:10
  • 1 @jaloplo No, the two timeouts are occurring at the same time - try yourself. The times do not add, the "both done" logs when both of them have called the callback. It's not a trick, it's exactly the same mechanism that Promise.all uses internally to wait for multiple asynchronous promise resolutions. – Bergi Commented Jun 29, 2019 at 14:13
 |  Show 10 more ments

3 Answers 3

Reset to default 11

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./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.

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.

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)

})()

本文标签: javascriptWhat are the advantages of using asyncawaitStack Overflow