3 ms·
First of all, thanks for all the answers everyone. So, for the case of JavaScript running in the browser (single-threaded and all), is my understanding correct
by endorphine 5y ago
First of all, thanks for all the answers everyone. So, for the case of JavaScript running in the browser (single-threaded and all), is my understanding correct that:
1. For something to be `await`ed on, it means that the calling function has to have the ability to be paused and continued later
2. Non-async functions cannot be paused right in the middle and resumed later. They're regular functions that will execute from start to finish by the main thread
3. In a hypothetical JavaScript implementation where a non-async function could `await`, the main thread would not be able to pause the calling function but instead it would keep executing it, blocking the thread, because there would be noone to execute that function that we would be `await`ing on (since there's only 1 thread and it's blocked). So it's a deadlock.
So, the difference between async and non-async functions in JavaScript, is that the former can be paused in specific points (pointed to by `await`).
- lioeters 5y agoI think it was a good question, seeing all the various answers people gave trying to explain and clarify. I enjoyed the discussion, and it helped deepen my understanding. As you said in another comment, what's confusing is that "await" actually means "Don't wait for the result, continue running other instructions, then come back to resume when the result is ready." > Async operations like promises are put into an event queue, which runs after the main thread has finished processing so that they do not block subsequent JavaScript code from running. The queued operations will complete as soon as possible then return their results to the JavaScript environment. From: General asynchronous programming concepts - https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts https://developer.mozilla.org/en-US/docs/Learn/JavaScript/As... --- About how async functions can be "paused and continued", it relates to the general concept of "continuations", which are: > ..constructs that give a programming language the ability to save the execution state at any point and return to that point at a later point in the program, possibly multiple times. > ..In C#, async and await "sign up the rest of method as the continuation, and then return to your caller immediately; the task will invoke the continuation when it completes." https://en.wikipedia.org/wiki/Continuation https://en.wikipedia.org/wiki/Continuation