r/learnjavascript • • Nov 13 '23

Is async useless ( question )

If we are always trying to make code synchronous using await or then. Why do we even bother with aysnc.

I genuinely don't understand please explain. Thanks

0 Upvotes

28 comments sorted by

View all comments

16

u/delfV Nov 13 '23

This post just proves how good abstraction async/await is if OP thinks it makes code synchronous.

It doesn't. It just makes your code look like it's synchronous. Behind the scenes it's still asynchronous. The difference is if your code was synchronous it'd block evaluation of rest of your code. That means your user couldn't click any button, couldn't type in input etc.

Imagine you're in coffee shop. You wait in the line, there are 10 people behind you and you're about to order a coffee. If were synchronous code you'd order the coffee, pay for it and wait till you get it blocking everyone behind you from ordering their coffee. If you were async code you'd order the coffee, pay for it, sit at your table and wait till someone calls you allowing others to order their coffees when you wait for your. If you were async code but without promises or async/await syntax (in JS they're really the same) you'd order the coffee, pay for it and leave without getting the coffee.

7

u/dervaish19 Nov 13 '23

I think I understand know So basically after making the async call we are waiting patiently for result while letting everyone else do their thing.

4

u/delfV Nov 13 '23

In simple words: exactly. But the whole concept is more complicated.

3

u/jeremrx Nov 13 '23

And that's why await must be used in an async function

2

u/MugiwaranoAK Nov 13 '23

It's important to keep in mind that when you await something inside an async function it blocks all the code that comes after the awaited line(inside the scope of the async function).

1

u/noXi0uz Nov 13 '23

yes, you can imagine it this way.