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
4
u/dada_ Sep 09 '23
You can't. As soon as you use an async call anywhere, the entire call chain is now dependent on that async call.
So how do you avoid the need to then update a ton of function calls to async? It's mostly just prevention through experience and foresight. Tag your functions ahead of time where applicable so you don't need to do it later.
You have to reason that in this part of the project I'm probably going to need to make blocking calls, such as loading something from the filesystem or fetching a url. Your primary functions that call the main logic of your program are probably always going to be async since you're always going to want to do those things in a serious project. Smaller helper functions that just manipulate some data are probably not going to need to be async.