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)
我究竟做错了什么?
顶级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 [我可以尝试的版本] 之间的某处启用)。
| 归档时间: |
|
| 查看次数: |
1341 次 |
| 最近记录: |