One can use await
keyword outside of async
functions with Top-level await and the happy news is you can use it today in node and REPL.
As of today, if we execute the bleow peice of code in node env:
1
|
|
We would see a: SyntaxError: await is only valid in async function
So, we would normally mitigate this by wrapping it in an async
function:
1 2 3 4 |
|
But with top level await it get's easier we could just do const answer = await Promise.resolve(42);
note that this will only work at the top level of modules only.
Well, Node.js v14.3.0 was released with the support of top-level await! But we always had a flag to enabled top-level await on the REPL, ever since node v10!
The --experimental-repl-await
enables experimental top-level await keyword support in REPL, so all you have to do is start the REPL with the flag node --experimental-repl-await
and that's it.
And within the script you could do something like:
1 2 3 4 |
|
1 2 3 |
|
You could execute this using node --experimental-top-level-await
.
TLDR: For REPL we would need --experimental-repl-await
and for mjs
scripts --experimental-top-level-await
as of today.