I have a short Node.js script where I require another package and call an async function from it and subsequently want to print the return value. If I simply await
the return value from the top level, then I'll get an error, saying that I can only use await
inside an async function itself. So apparently the way to go is like this:
async function main() {
foo = await someOtherAsyncFunc();
console.log(foo);
}
main()
Or:
(async function() {
foo = await someOtherAsyncFunc();
console.log(foo);
})();
Or:
(async () => {
foo = await someOtherAsyncFunc();
console.log(foo);
})();
(Credit to VLAZ in chat https://chat.stackoverflow.com/transcript/message/54186176#54186176)
This works - but I want to understand the reasons behind it a little bit more: I'm used to not being able to directly use await
from the top level. However, I'm also used to having to call some special library function to actually "venture" into async from the top level. In Python, see asyncio.run
for example. What's the point of requiring await
to be inside an async function - if I can then call just any async function from the top level? Why then isn't await
available at top level, too?