Top-level await does not work with node 14.13.-
Asked Answered
A

2

14

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?

Angelitaangell answered 26/11, 2020 at 8:8 Comment(0)
S
18

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

Soinski answered 26/11, 2020 at 8:11 Comment(1)
FWIW, I go into using ESM with Node.js, and separate go into top-level await, in some detail in Chapters 13 and 19 of my new(ish) book, JavaScript: The New Toys. Links in my profile if you're interested.Soinski
E
1

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

Edwardedwardian answered 2/12, 2021 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.