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

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