顶级 await 不适用于节点 14.13。-

Kar*_*lek 5 javascript node.js top-level-await

我有节点 14.13.0,即使有--harmony-top-level-await,顶级 await 也不起作用。

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

我究竟做错了什么?

T.J*_*der 8

顶级await仅适用于 ESM 模块(JavaScript 自己的模块格式),不适用于 Node.js 的默认 CommonJS 模块。从您的堆栈跟踪来看,您正在使用 CommonJS 模块。

你需要把"type": "module"package.json或使用.mjs的文件扩展名(我推荐使用的设置)。

例如,有了这个package.json

{
  "type": "module"
}
Run Code Online (Sandbox Code Playgroud)

main.js

const x = await Promise.resolve(42);
console.log(x);
Run Code Online (Sandbox Code Playgroud)

node main.js 显示 42。


旁注:您不需要--harmony-top-level-awaitv14.13.0。在该版本中默认启用顶级等待(它在 v14.4 和 v14.9 [我可以尝试的版本] 之间的某处启用)。

  • FWIW,我将介绍如何将 ESM 与 Node.js 结合使用,并单独介绍顶级“await”,详细信息请参阅我的新书 *JavaScript:新玩具* 的第 13 章和第 19 章。如果您有兴趣,可以在我的个人资料中找到链接。 (2认同)