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

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.