r/learnjavascript • • 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?

5 Upvotes

43 comments sorted by

15

u/guest271314 Sep 09 '23

How does one avoid async spreading throughout your code?

If you prefer you can use then() and catch().

I cannot treat the calling function as being a synchronous function.

You cannot treat the return value as synchronous because the process that returns or yields the value is not synchronous.

Just practice handling asynchronous processes.

16

u/alzee76 Sep 09 '23

How does one avoid async spreading throughout your code?

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 function bar(), and foo() is miles deep on a synchronous call stack, you would wrap the entire function body of foo() in an IIFE.

Before:

function foo() {
  // stuff
  await bar(); // Crap, this won't work..
  // more stuff
}

After:

function foo() {
  (async () => {
    // stuff
    await bar(); // This will work now.
    // more stuff
  })();
}

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."

5

u/lost12487 Sep 10 '23

This only works if you don't care about what the foo function is returning. I'd also argue that if this is the actual behavior you really want then just forgoing async/await and using promises is way cleaner than this.

function foo() {
  // stuff
  bar().then(() => {
    // more stuff
  });
}

1

u/alzee76 Sep 10 '23

This will work but it is likely to lead you down the very path of ever deeper then().. nesting that async/await was introduced to get rid of.

1

u/lost12487 Sep 10 '23

Just make the callback function in the .then() async if you need to do more asynchronous calls after the first one...I don't understand why you would ever reach for an IIFE in this scenario.

0

u/alzee76 Sep 10 '23

I don't understand why you would ever reach for an IIFE in this scenario.

Likewise, I can't understand why anyone would prefer the "ugly" Promise syntax to the "clean" async/await syntax, now that we have the option.

2

u/Masterflitzer Sep 10 '23

doesn't this defeat the point if the async function? how do you get the result?

2

u/alzee76 Sep 10 '23 edited Sep 10 '23

Ultimately, there is no solution to the OPs problem except to start refactoring everything from the point that he needs to make the async call back "up" (and laterally) to make everything async. This is what he was complaining about having to do, though.

To answer your question, the "point" in this context is to be able to call the async function from a non-async function, which is impossible without doing this or similar hackery. Getting the result to a function isn't a requirement, many functions do not return anything, and this is intended for those cases. It allows you to at least call the thing without refactoring however many functions earlier in the call stack, and every function that calls any of those functions.

If your async function returns a result that you need, and you still refuse to refactor for some reason, you have a long and painful road ahead. You should really just refactor, which is what the OP was complaining about having to do.

1

u/Masterflitzer Sep 10 '23

thx I just wanted to make sure I understand the code correctly

1

u/irontea Sep 10 '23

This is exactly the way to do if you don't want to make the calling function async. Simple and doesn't require you changing a bunch of files

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.

1

u/Count_Giggles Sep 09 '23

The web is fast and we have ways to make the ux bearable even if a request takes a few seconds to be processed. i promise you async await is wayyy more ergonomic than things used to be and personally going back to chaining .then is also not an option.

const getAllUsers = async () => {
    const response = await fetch('https://api.example.com/users');

    if (!response.ok) { 
        throw new Error('Failed to fetch user data'); 
    }
    
    const data = await response.json(); 
    return data; 
};
    
const users = await getAllUsers();

i find this to be perfectly readable and self documenting. Of course i speak from a position of having dealt with this for quite some time but still. If you want acess to the web. things will be of asynchronous nature. But i get it. From time to time we all gotta rant a bit

5

u/SocksOnHands Sep 09 '23

My problem isn't with using async/await - it's that every function up the call chain needs to be made async, even if they are not really behaving in a way that appears to be asynchronous. Either way, the same amount of time might have been spent doing the same thing because of the await waiting to resolve, but now everything needs to be refactored to be async.

2

u/jaypeejay Sep 09 '23

I don't follow, how can a function that invokes an asynchronous function be considered synchronous?

2

u/SocksOnHands Sep 09 '23 edited Sep 09 '23

I know JavaScript is not the same as other languages, but a similar behavior in something like C would be waiting on a mutex. I know, under the hood, these are implemented differently, since JavaScript is single threaded, but if everything happens within the function call and completes before returning, then to an outside observer, a function using await and a function not using it will appear to behave in a similar way. The difference is that, because the function was made to be async (despite everything completing before returning), the calling function now also needs to use await, so that function now needs async, etc.

See a comment someone else had made, where their example of a validation changing later in development to now need to make an API call, when it used to be a simple function. Now it will require rewriting a bunch of other stuff to also be async, when it hadn't been before. The code was first written with the assumption that everything could have been done using simple synchronous functions, but now everything that is even only indirectly related will need to be rewritten to be async.

1

u/CrawlToYourDoom Sep 09 '23

Are you encapsulating multiple responsibilities in one function? Because that’s pretty much the only thing that would create this problem.

2

u/Count_Giggles Sep 09 '23

could you give me a concrete example? i am not sure what you when you phrase it like that

2

u/ic6man Sep 09 '23

That’s not really true. You just don’t understand how to deal with async well enough yet.

1

u/Reaver75x Sep 10 '23

What scenario would you need so many nested functions where it would get annoying?

1

u/SocksOnHands Sep 10 '23

One example that I can think of might be a game, which would typically have a call chain that might look something like: game loop -> state manager -> scene graph -> entity nodes -> entity components -> helper functions -> etc. Now, if any components are forced to make an async call, everything up the chain will need to be async. Of course, with a game, something like an HTTP requests should be done asynchronously, since everything should complete within a single animation frame, but async functions in some dependency might exist that is expected to complete within a short time span, since async isn't limited to only being used for long running requests.

1

u/33ff00 Sep 09 '23

Is this frontend or node?

0

u/SocksOnHands Sep 09 '23

I mean, in general - if a function uses await, it needs to be async.

3

u/carcigenicate Sep 09 '23

Yes. Async tends to "infect" code that uses it. Usually, you have purer functions that just deal with data, async functions that get data, and then something like a async main procedure that calls both types of functions.

This is basically the same "problem" you have with IO in Haskell, where functions that use a function returning an IO object must themselves also return an IO object. You're meant to separate out the pure and IO/async functions so the IO/async code can be isolated.

1

u/33ff00 Sep 09 '23

Well there’s various approaches I use depending on context, but ok

4

u/[deleted] Sep 09 '23

A function using async/await is no different than a function returning a promise. If you need a function to return a promise, other parts of your codebase will have to act accordingly. There’s really no getting around this.

1

u/oze4 Sep 09 '23

I'm having a hard time understanding how this happens. Can you provide an example? Like how does a sync call suddenly need to be async?

1

u/EnteringSectorReddit Sep 09 '23 edited Sep 09 '23

Well, let's say first you need just to check if IBAN is correct. Just a simple sync function.

Few month later, company pay to access API that actually know if this IBAN not only correct, but also exist and what bank are behind it.

Well, now you need to add async HTTP call to your sync function.

2

u/oze4 Sep 09 '23

I guess I don’t understand how you were making that check before the API existed?

Either way, I see your point. I’m pondering ways to get around it but idk if you can.

1

u/EnteringSectorReddit Sep 09 '23

Replace IBAN with credit card number.

There is a simple function that checks if this is a theoretically valid number. And it's ok for MVP.

When you go to prod, you need more advance check - to see if card really exist, if your bank can transfer money there and so on.

1

u/oze4 Sep 09 '23

Ah that makes sense. You were just using an algo to check if it's a valid CC number - I know what you're talking about.

That makes sense, and yeah, def sounds painful.

1

u/EnteringSectorReddit Sep 09 '23

Yeap, this is a hurdle.

Sometimes you need to either create new function or reinvent the wheel instead of adding additional 10 asyncs in 10 modules.

1

u/[deleted] Sep 10 '23

I mean it's far better than the alternatives.

1

u/darthruneis Sep 10 '23

The underlying reason why async tends to bubble up the call chain like this is so that your code continues to execute in the correct order.

Otherwise, the lines after the async call will execute before the async call has finished. This is a huge source of issues and is often hard to reason about, except in cases of optional or fire and forget operations, where the caller cares that it started but not that it finished.

This situation then bubbles up throughout the call stack, requiring everything to be aware of async so that the code can execute in the intended order.

There is no way around this.

1

u/irosion Sep 10 '23
(async () => myAsyncFunc())() 

or

myAsyncFunc().then((r) => doSomething(r))

1

u/Reaver75x Sep 10 '23

What scenario would you need so many nested functions where it would get annoying?

1

u/shgysk8zer0 Sep 10 '23

Would you rather the old way of doing this, such as event listeners or maybe polling using some shared variable in scope?

And there are many ways of dealing with async inside of synchronous code, such as Promises or an async IIFE. You just have to think about which parts actually need to be async and which don't. You basically only need to worry about parts where I return value is determined by an async function, not where maybe side effects happen async but you can return something before those complete - example might be logging... You can return while that takes place in the background.

1

u/[deleted] Sep 10 '23

This really doesn't have anything to do with async/await. You'd essentially have the same problem with .then() chaining or pyramid of doom style callbacks.

1

u/jaypeejay Sep 09 '23

It sounds like you might be violating the single responsibility principle? Hard to tell without an example.

0

u/shuckster Sep 09 '23
async function fetcher() {
  // ...
}

function handleResponse(res) {
  // ...
}

function handleFailure(reason) {
  // ...
}

fetcher()
  .then(handleResponse);
  .catch(handleFailure);

0

u/[deleted] Sep 09 '23

This isn’t true. An async function can be called like a synchronous function. This happens all the time

-7

u/ic6man Sep 09 '23

Yeah. So what. And the world is round. Asynchronous is asynchronous. If you don’t like programming you can always flip burgers.