Search code examples
javascriptnode.jstop-level-await

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?


Solution

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