One can use the 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 below piece of code in node env:
await Promise.resolve(42);
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:
(async function() {
const answer = await Promise.resolve(42);
// answer would be 42
}());
But with top level await it gets easier - we could just do const answer = await Promise.resolve(42); Note that this will only work at the top level of modules only.
Node.js v14.3.0+ Support
Node.js v14.3.0 was released with the support of top-level await! But we always had a flag to enable 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.
Usage in Scripts
// home.mjs
export function home() {
return 'Hello home!';
}
// index.mjs
const home = await import('./home.mjs');
console.log(home());
You could execute this using node --experimental-top-level-await.
TL;DR: For REPL we would need --experimental-repl-await and for .mjs scripts --experimental-top-level-await as of today.
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.