Hacker News new | past | comments | ask | show | jobs | submit login

What problem would arise if synchronous functions could use await?



Languages with async/await do usually give you a way to bridge between async and sync code, but generally through a function (like this one [1] in Python) rather than allowing you to await from sync code. The problem is that sync code isn't being scheduled by the event loop. You need to use a function that's aware of the event loop's internals and can schedule your coroutine, and use a rendezvous or another synchronization primitive to wake up your sync code when the coroutine is done.

One could imagine a language where an await from sync code was syntactic sugar for such a function call, but generally the async/await syntax serves as a way to deliberately segregate your sync and async code. So that would defeat the purpose. At that point it might make more sense to design the language like Go and make everything async. (Preemptive runtimes like Java's virtual threads are another option.)

There was a good blog post I want to link here where the author argued that async/await is making explicit the fundamental property of some functions being expensive, as a counterpoint to TFA, but I haven't been able to find it again. But they made the case that expensive operations are fundamentally viral, and async/await was only making this explicit and wasn't unjustified overhead as some argue.

[1] https://docs.python.org/3/library/asyncio-task.html#asyncio....


Couldn't the browser simply internally turn this:

    function f1() {
        x = await fetch('something');
        ...
    }
Into this:

    function f1() {
        fetch('something').then(x => {
            ...
        });
    }


No, it cant. These 2 are semantically not eqivalent, because in async version caller of f1() is resumed only once fetch has completed. In your callback version it will be resumed immediately.

Also think how this should be translated: function f1() { x = await fetch('something'); return x + 1; }


If they await, they’re no longer synchronous functions


The difference would be that you still can call the function without await.

So this would be possible:

    async function f1() {
        f2();
    }

    function f2() {
        await fetch('something');
        ...
    }
Instead of having to async each and every function and await each and every function call:

    async function f1() {
        await f2();
    }

    async function f2() {
        await fetch('something');
        ...
    }
Which is what TFA complains about and what indeed is a pain in the ass.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: