Ask HN: Why can’t await be used from non-async functions?


W3Schools
Ask HN: Why can’t await be used from non-async functions?
by endorphine on Hacker News.
I’m trying to wrap my head around async/await and how it works under the hood, be it JavaScript, C# or others. From what I understand, in JavaScript at least, putting `await foo()` inside an async function, splits the calling function in two, with the 2nd half being converted to a callback. (Pretty sure this is full of errors so please correct me where I’m wrong) Why can’t non-async functions use await()? I’ve also read that await() basically preempts the currently running function. How does this work? Update: I’m re-reading https://ift.tt/P05DJfb… and I think the answer lies somewhere in this paragraph, but I can’t wrap my head around it yet: > The fundamental problem is “How do you pick up where you left off when an operation completes”? You’ve built up some big callstack and then you call some IO operation. For performance, that operation uses the operating system’s underlying asynchronous API. You cannot wait for it to complete because it won’t. You have to return all the way back to your language’s event loop and give the OS some time to spin before it will be done. Once operation completes, you need to resume what you were doing. The usual way a language “remembers where it is” is the callstack. That tracks all of the functions that are currently being invoked and where the instruction pointer is in each one. But to do async IO, you have to unwind and discard the entire C callstack. Kind of a Catch-22. You can do super fast IO, you just can’t do anything with the result! Every language that has async IO in its core—or in the case of JS, the browser’s event loop—copes with this in some way. […] I don’t get the “You cannot wait for it to complete because it won’t.” or the “But to do async IO, you have to unwind and discard the entire C callstack” parts. I’m also using these resources, they help but I’m not there yet: – https://ift.tt/ZrniAxP… – https://www.youtube.com/watch?v=KmMU5Y_r0Uk


W3Schools

Leave a comment