I am on running Node version 14.15.3
Welcome to Node.js v14.15.3.
I thought it was cool that you could use await
now in top level scripts, so I tried it. To not my surprise, it didn’t work.
const myfunc = async () => { return new Promise((res, rej) => { setTimeout(() => {res()},1000) }) } await myfunc();
SyntaxError: await is only valid in async function at wrapSafe (internal/modules/cjs/loader.js:979:16) at Module._compile (internal/modules/cjs/loader.js:1027:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Module.load (internal/modules/cjs/loader.js:928:32) at Function.Module._load (internal/modules/cjs/loader.js:769:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47
Not sure what else to say. It just doesn’t work.. Did it break? Did it ever really work?
Advertisement
Answer
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:
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
Files ending in .mjs.
Files ending in .js when the nearest parent package.json file contains a top-level field “type” with a value of “module”.
Strings passed in as an argument to –eval or –print, or piped to node via STDIN, with the flag –input-type=module
If you use one of the above approaches to enable ES6 modules within your project, then you’ll be able to use top-level await:
script.mjs (note the .mjs):
const myfunc = async () => { return new Promise((res, rej) => { setTimeout(() => {res("Hello")}, 1000) }) } console.log(await myfunc()); // logs "Hello" after ~1s