The question: Is there, (and if yes, to what extent) a computational overhead in the engine runtime to declare a function as async
and to eventually await
as compared to a regular function's return statement ?
async function foo() {
var x = await bar(); // <--- bar() is non-blocking so await to get the return value
return x; // the return value is wrapped in a Promise because of async
}
Versus
function foo() {
var x = bar(); // <--- bar() is blocking inside its body so we get the return value
return new Promise(resolve => { resolve(x); }); // return a Promise manually
}
Context:
Due to the asynchronous direction taken by Javascript (and i.e. Nodejs), why did they not consider every function to be asynchronous (as per async
keyword) by default ?
This way, people could just decide to treat any function call as a Promise
and play the asynchronous game, or just await
what is necessary.
I suppose that await
-ing within a function body creates the overhead of stacking the local function's scope whereas the normal event loop proceeds when the function returns and does not have to push the inner function scope to the stack ?
This comes down to a bonus question : in a complex hyerarchy of classes that (somewhere deep) requires one synchronous IO operation (see note) that would ideally be await
'ed. It is only possible if that method is marked as async
. Which in turn required the calling function to be async
to be able to await
it again and so forth. Thus, everything marked async
and await
when needed... How to deal with such a scenario ?
Note: Please do not argue about the necessity of not-doing any sync operations as this is not the point.
Note 2: This question is not about what is await
or async
nor when it executes. This question is about performance and the internals of the language (even though multiple implementations exist, there may be a inherent semantic overhead to the concept).
await
will also work for non-promise values. "How to deal with such a scenario ?" There is not a new way to handle this situation.async/await
is just syntactic sugar for promises. You do exactly the same thing you do when dealing with promises.async function
s are still asynchronous - non-blocking, that's the whole point of concurrency in node.js.await
placed everywhere: that would be an absolutely horrible idea.