logoalt Hacker News

bre1010today at 5:23 PM3 repliesview on HN

I wish the key word was instead dontawait and was used inversely to how await is used. 99% of the time I'm using an async function, despite however slow it is, there's nothing for my code to do but wait for it to finish. But if for some reason I would like the next line of code to run before the current one is done, I'll let you know.

Like, why can't my sync function await something asynchronous? If it has to lock up the whole thread while that function executes, that's fine because that's how it was going to work anyway 99% of the time


Replies

enragedcactitoday at 5:45 PM

> Like, why can't my sync function await something asynchronous?

The answer, at least for Python, is that it is an intentional limitation because the alternatives introduce some quite bad trade-offs.

Option 1: your awaited promise goes into the main async event loop. This is bad because it means that your single-threaded sync function now needs to be thread-safe, and so does any sync code that calls your sync function despite it not even knowing that you're doing anything async. This is essentially unworkable without throwing away the option of writing non-thread-safe code.

Option 2: Your awaited promise goes into its own new event loop that only contains sibling and child promises. There's nothing technically stopping someone from doing this[1], but now you've lost a ton of the value of async because you will inevitably end up with a ton of siloed event loops that leave the process idle despite other async tasks existing that could run. Effective async code needs to share an event loop at as high of a level as possible, which means tainting as many methods with async as possible. At that point, you might as well enforce it at the language level and avoid the inevitable pain and fragmentation that comes from other devs across the ecosystem mixing sync and async code.

[1] https://pypi.org/project/nest-asyncio/

As explained by Guido: https://github.com/python/cpython/issues/66435#issuecomment-...

show 1 reply
sheepttoday at 6:23 PM

At least in JavaScript, it's nice to be able to see explicitly where you can expect the function to yield, so it's clear when race conditions can occur, or if you're calling it in a loop, whether you should consider running things in parallel.

Plus, you probably don't want to lock up the whole thread if you're writing anything more than a quick script, like a web server or a GUI.

axustoday at 5:28 PM

Like the & at the end of a shell command?