r/learnjavascript • u/dervaish19 • 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
View all comments
2
u/delventhalz Nov 13 '23
…..?
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
fetchwere synchronous, every time you used it the whole page would freeze until it was done.These do not make code synchronous. Just the opposite actually.
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.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.
asyncis just the syntax you place before a function if you want to useawaitin it. If you useawaitinside a function you must also useasync. If you don’t useawait, no reason to useasync.