顶级 await 在最新的 Node.js 中不起作用

vit*_*y-t 7 node.js async-await

awaitNode.js 中是否仍然不支持顶级(2020 年 1 月,Node.js 13.5.0)?

我试过一些教程,比如这个,但仍然没有运气,总是得到同样的错误:

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
Run Code Online (Sandbox Code Playgroud)

整个文件内容:

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
Run Code Online (Sandbox Code Playgroud)

我尝试使用"type": "module"in package.json,并将文件重命名为test.mjs,但仍然出现相同的错误,即使使用最新的 Node.js 13.5.0

我究竟做错了什么?

Kla*_*con 11

根据此问题跟踪器此博客文章,顶级 await 在 Node v13.3+ 中的 flag 后面可用--harmony-top-level-await。您启用的模块标志仅适用于 ESM 模块,而不适用于顶级等待。

  • 我使用的是 Node v14.7.0,在 `node --help` 中找不到任何 `--harmony` 标志,但有一个 `--experimental-repl-await` 标志对我有用。 (4认同)