Karel Bílek
Karel Bílek

Reputation: 37694

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?

Upvotes: 15

Views: 19317

Answers (2)

user16125753
user16125753

Reputation:

T.J. Crowder answer is right, but I recommend changing all the .js to .mjs

For example, if you are working with NextJS like me, you will see a problem that files in the .next directory use CommonJS (.next is generated using npx next build) and their extensions are js so it raises an error when the .next files use require()

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074979

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

Upvotes: 20

Related Questions