Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top-level await does not work with node 14.13.-

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?

like image 513
Karel Bílek Avatar asked Nov 26 '20 08:11

Karel Bílek


People also ask

How does top level await work in NodeJS?

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:

How does top-level await work with modules?

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.

Does await work with ES6 modules?

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.

What is top level await in PostgreSQL?

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).


1 Answers

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).

like image 174
T.J. Crowder Avatar answered Sep 30 '22 01:09

T.J. Crowder