Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top-level await doesn't work in the latest Node.js

Is top-level await still not supported in Node.js (Jan 2020, Node.js 13.5.0)?

I've tried some tutorials, like this one, but still no luck, always getting the same error:

D:\NodeJS>node --experimental-modules test.js
(node:17724) ExperimentalWarning: The ESM module loader is experimental.
file:///D:/NodeJS/test.js:9
await test();
^^^^^

SyntaxError: Unexpected reserved word

The entire file content:

function test() {
}

await test();

I have tried using "type": "module" in package.json, and renaming file into test.mjs, but still the same error, even with the latest Node.js 13.5.0

What am I doing wrong?

like image 616
vitaly-t Avatar asked Jan 03 '20 21:01

vitaly-t


People also ask

Does Nodejs support top level await?

js modules.

How do you use await at top level?

Top level await You can use the await keyword on its own (outside of an async function) within a JavaScript module. This means modules, with child modules that use await , wait for the child module to execute before they themselves run. All while not blocking other child modules from loading.

What version of Node supports async await?

Node. js 7.6 has shipped with official support for async / await enabled by default and better performance on low-memory devices.

Does async await work in node js?

Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.


2 Answers

node --experimental-repl-await works for the Node REPL

edit: the Node 16 REPL accepts top level await by default, you don't need the experimental flag anymore

like image 99
Antoine Weber Avatar answered Sep 28 '22 22:09

Antoine Weber


Per this issue tracker and this blog post, top-level await is available in Node v13.3+ behind the flag --harmony-top-level-await. The module flag you're enabling is only for ESM modules and not for top level await.

like image 44
Klaycon Avatar answered Sep 28 '22 21:09

Klaycon