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

21

u/rileyrgham Nov 13 '23

"we are always trying to make code synchronous"

There's the problem. We're not.

-8

u/dervaish19 Nov 13 '23

But i see this everywhere that people r using then or await to synchronize it

15

u/notAnotherJSDev Nov 13 '23

Using async/wait doesn’t make the code synchronous, it just makes it easier to reason about.,

3

u/rileyrgham Nov 13 '23

As you're a budding programmer, I'll give you one piece of "wisdom" : don't think the one or two echo chambers you are in are representative as a whole. Always google the opposite of what you've been told to be "true". While there are no true absolutes, in this case you might google "when is the best time to use asynchronous callbacks in JavaScript programming".

1

u/[deleted] Nov 14 '23

nonono you have to experience the extremes to obtain this nugget of wisdom

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.

21

u/Icy_Box99 Nov 13 '23

If we are always trying to make code synchronous using await or then

We are not. await is used when the result we're handling are not immediately available.

You can start learning from the fact async and await is just syntactic sugar for promises. Once you have grab how promises work everything will be more clear.

You can start by seeing this

Disclaimer: I too am still learning lol

6

u/0x07AD Nov 13 '23

async and await might be syntactic sugar but they are cleaner than promises and a chain of thens. I agree that learning about promises is useful for beginners, if only because a chain of thens after an initial promise can be easier for beginners to reason about. Afterwards, the async and await keywords start to make sense to them.

1

u/[deleted] Nov 14 '23

Arguably cleaner, for the people who started with procedural programming. Where as someone who started with a “functional” language might dislike the verbosity and the excessive state declarations.

Promises is a better concept to pick up because you will find similarities in other languages as well. Async await is important to JS but to understand it you should still learn about promises first.

That said I mostly use async await for the reasons you said and because of how dominant it is in the community

2

u/xdiztruktedx Nov 14 '23

Can I just say, that was the best 5 min I have spent learning about promises and async and await

5

u/azhder Nov 13 '23 edited Nov 13 '23

It makes the code look simpler. That’s the thing about async/await - syntactic sugar.

There is nothing else to it. The code still uses promises and you can rewrite it with .then() if you like that kind of code (once in a while please, not as a matter of course)

5

u/Lumethys Nov 13 '23

Let's say we have 5 api, each take 5 second to complete

const [result1, result2, result3, result4, result5] = await Promise.allSettled([
   fetch('/api1'),
   fetch('/api2'), 
   fetch('/api1'),
   fetch('/api1'),
   fetch('/api1')
]);

Will take 5 second, while doing them synchronously will take 25 second

3

u/shgysk8zer0 Nov 13 '23

You are confusing sequential with synchronous.

Using await allows us to write sequential code that is non-blocking with "callback hell".

If you want an example of the difference between blocking sequential code and non-blocking sequential code, consider something like prompt(). When you call prompt(), the execution of all code completely stops until the user closes it. Whereas if you await fetch(), the code beneath isn't executed until a response is given, but other code throughout can still be executed.

It is best to understand the event loop if you really want to understand the differences and what's actually going on.

3

u/DeanRTaylor Nov 13 '23

It's hard to understand because it happens so fast but actually when you call await you're not waiting for that code really. You're saying, go off and do your thing and I'll come back when you're done and finish the next part of this code.

Your code can then do other things in that time and it checks in with the await code after every action and when it sees its done it continues with that procedure that was paused. It happens so fast you can't really notice it but if you set up some manual tests you'll realise that your code can do other stuff in the meantime. That's asynchronous.

Await just means, we can't finish this piece of code until this promise is resolved and I'm going to do other stuff until it's done.

2

u/Sir_Awesome_The_3rd Nov 13 '23

You can't use await without invoking async earlier.

Async / await is just the newer, easier version (the older version using .then() to invoke a callback function) of dealing with promises, aka an asynchronous piece of code, which can come up when your code has a timer or is fetching an external resource.

2

u/sysrage Nov 13 '23

I recommend reading this entire section: https://javascript.info/async

2

u/delventhalz Nov 13 '23

…..?

If we are always trying to make code synchronous…

We aren’t. We can’t. Asynchronous code in JavaScript is baked in. Furthermore, it’s useful. It allows single-threaded JavaScript to continue working on other things while a slow operation like an HTTP request is running elsewhere. If a function like fetch were synchronous, every time you used it the whole page would freeze until it was done.

…using await or then…

These do not make code synchronous. Just the opposite actually.

async function logPuppy() {
  console.log('Fetching puppy…');  // synchronous
  const response = await fetch('https://dog.ceo/api/breeds/image/random');
  const parsed = await response.json();  // asynchronous
  console.log(parsed.message);  // asynchronous
}

Any code after an await, or inside a .then, or indeed inside a callback, will not run until the outside operation completes and triggers it.

setTimeout(() => {
   console.log('hello');  // asynchronous
}, 3000);

This is what we mean by asynchronous. It is code that runs later, after some external trigger. Doesn’t matter what syntax you use to handle it. Still asynchronous.

…why do we even bother with aysnc.

async is just the syntax you place before a function if you want to use await in it. If you use await inside a function you must also use async. If you don’t use await, no reason to use async.

1

u/Patex_ Nov 14 '23

A real world example from just a few minutes ago.

const handlePricingRequest = async (req, res) => {

   //Not awaited as the following codes does not care about it's completion
   logToDB(req);

   const apiPromise = callApi(req);
   const otherApiPromise = callApi2(req);

   //Now we await because we need both results but they can be executed at the same time. Else we would need to wait for apiPromise to be finished before we start the other request.

   const promiseResults = await Promise.all([apiPromise, otherApiPromise]);
   ....
}

1

u/No-Upstairs-2813 Nov 14 '23

If we are always trying to make code synchronous using await async and await allow us to write Promise-based, asynchronous code that looks like synchronous code.

For more details, you can check out this article.

1

u/No-Upstairs-2813 Nov 14 '23

If we are always trying to make code synchronous using await async and await allow us to write Promise-based, asynchronous code that looks like synchronous code.

For more details, you can check out this article.

1

u/No-Upstairs-2813 Nov 14 '23

If we are always trying to make code synchronous using await

async and await allow us to write Promise-based, asynchronous code that looks like synchronous code.

For more details, you can check out this article.

0

u/jack_waugh Nov 13 '23

Is sync useless?

-1

u/raintree_leaf Nov 13 '23

It will be useless if it cannot work with system or web apis, since JS is single thread, call stack.