DEV Community

Discussion on: Avoid async/await hell

Collapse
 
thumbone profile image
Bernd Wechner • Edited

I have to admit I am left wondering who would write code like this to begin with:

const user = await getUser(id);
const items = await getItems();
return { user,  items, };
Enter fullscreen mode Exit fullscreen mode

it defeats the whole point of async!

And of course anyone who's using async functions must perforce have read some intro on Promises (and I admit I had to read many about 20 times before I think I finally got it) will knowabout Promise.all() and Promise.allSettled() as they indeed the standard means of waiting on several promises at once.

I'd be cautious with this:

and up to twice as fast because we're running all the promises in parallel

It is mostly true. But it does hide some asusmptions too. It's important to understand that an async function consumes time in two ways:

  1. Executing Javascript code
  2. Waiting on Browser promises (generally HTTP requests, maybe user input, maybe a websocket response whatever, but the browser is off doing something).

The difference is crucial because 1. remains blocking regardless of its async status (the JavaScript engine not supporting true parallelism or multthreading at all), while category 2. work isn't and actually forms the wellspring of true Promises (from the Browser to the JavScript engine).

And that is relevant to that comment, because it can happen that two async functions poorly written, when run in parallel yield little benefit at all. That would be exceptional of course and falls within the purvey of the claim ( "up to twice" and I said that mostly true, in fact I'll go one better, it's quite insightful, because in the best case the two functions have identical cost in time and then you'd halve the net wait, as long as their time cost is in category 2.)

The reason for that distinction is very relevant when a function is expensive because of JavaScript processing time. In that instance however, the setTimeout function becomes very important as a means of relaxing your expensive code's strangle-hold on the JavaScript engine.

I discuss some of that here:

dev.to/thumbone/deferring-to-the-u...

Collapse
 
judionit profile image
Judicaël Andriamahandry

yes yes definitely true, learned some on your comments, thanks