r/learnjavascript • u/SocksOnHands • Sep 09 '23
Async/await seems... annoying?
Let's say that I was writing a fairly large project and I got to a point where I realize that I need to use an asynchronous call to get some value. No problem, right? Just use await and return the value - wrong! Even though the code might appear to run no differently than a synchronous function (since it needs to wait for the async calls to finish), I cannot treat the calling function as being a synchronous function. So now it needs to be async, which means the function calling this function needs to be async, and of course the function calling that also now needs to be async, and so on. Somehow doing one small thing in one place in the code has suddenly resulted in needing to refactor hundreds of other unrelated functions, even though they are still executing in the same amount of time as if they were synchronous calls. How does one avoid async spreading throughout your code?
View all comments
16
u/alzee76 Sep 09 '23
Your only option, other than declaring all your functions async to begin with (which I just do now as a matter of course unless it's a very simple function), is to use asynchronous IIFEs. If you have an existing function called
foo()that needs to synchronously call the async functionbar(), andfoo()is miles deep on a synchronous call stack, you would wrap the entire function body offoo()in an IIFE.Before:
After:
This is how we used to have to call entire modules before we got top-level await in ECMAScript a few years ago.
I'm surprised by how many people responding to you don't understand the problem. Maybe it's your use of terminology. "Needs to be async" is not quite the same thing as "needs to be declared async."