I have node 14.13.0, and even with --harmony-top-level-await
, top-level await is not working.
$ cat i.js
const l = await Promise.new(r => r("foo"))
console.log(l)
$ node -v
v14.13.0
$ node --harmony-top-level-await i.js
/Users/karel/i.js:1
const l = await Promise.new(r => r("foo"))
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:791:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
What am I doing wrong?
Top-level await works within ECMAScript modules. By default, NodeJS doesn't use these, and instead, it uses CommonJS modules. There are a few ways to enable ES6 modules in your node project though as outlined here:
With top-level await, modules are still executed in the same post-order fashion, but the execution of a module can be deferred until an awaited promise is resolved. This means that the sibling modules can continue their execution without being hung up on the await of their leftest sibling (s). This addresses the concern of blocking execution.
Top-level await works within ECMAScript modules. By default, NodeJS doesn't use these, and instead, it uses CommonJS modules. There are a few ways to enable ES6 modules in your node project though as outlined here: Files ending in .mjs.
With top-level await, modules are still executed in the same post-order fashion, but the execution of a module can be deferred until an awaited promise is resolved. This means that the sibling modules can continue their execution without being hung up on the await of their leftest sibling (s).
Top-level await
only works with ESM modules (JavaScript's own module format), not with Node.js's default CommonJS modules. From your stack trace, you're using CommonJS modules.
You need to put "type": "module"
in package.json
or use .mjs
as the file extension (I recommend using the setting).
For instance, with this package.json
:
{
"type": "module"
}
and this main.js
:
const x = await Promise.resolve(42);
console.log(x);
node main.js
shows 42.
Side note: You don't need --harmony-top-level-await
with v14.13.0. Top-level await is enabled by default in that version (it was enabled in v14.8.0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With