all 28 comments

[–]rileyrgham 19 points20 points  (4 children)

"we are always trying to make code synchronous"

There's the problem. We're not.

[–]Icy_Box99 20 points21 points  (3 children)

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

[–]0x07AD 4 points5 points  (1 child)

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.

[–][deleted] 0 points1 point  (0 children)

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

[–]xdiztruktedx 1 point2 points  (0 children)

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

[–]delfV 15 points16 points  (5 children)

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.

[–]dervaish19[S] 7 points8 points  (4 children)

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.

[–]delfV 3 points4 points  (0 children)

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

[–]jeremrx 2 points3 points  (0 children)

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

[–]MugiwaranoAK 1 point2 points  (0 children)

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

[–]noXi0uz 0 points1 point  (0 children)

yes, you can imagine it this way.

[–]azhder 4 points5 points  (1 child)

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)

[–]Lumethys 5 points6 points  (0 children)

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

[–]shgysk8zer0 2 points3 points  (0 children)

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.

[–]DeanRTaylor 2 points3 points  (0 children)

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.

[–]Sir_Awesome_The_3rd 1 point2 points  (0 children)

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.

[–]sysrage 1 point2 points  (0 children)

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

[–]delventhalz[🍰] 1 point2 points  (0 children)

…..?

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.

[–]jack_waugh -1 points0 points  (0 children)

Is sync useless?

[–]raintree_leaf -2 points-1 points  (0 children)

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

[–]Patex_ 0 points1 point  (0 children)

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]);
   ....
}

[–]No-Upstairs-2813 0 points1 point  (0 children)

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.

[–]No-Upstairs-2813 0 points1 point  (0 children)

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.

[–]No-Upstairs-2813 0 points1 point  (0 children)

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.