小编con*_*ion的帖子

如果当前运行时支持,请使用顶级等待

顶级等待支持已在 14.3.0 via--experimental-top-level-await和更高版本中添加到 Node.js 中--harmony-top-level-await

问题

如果当前 Node.js 运行时支持,我需要在 ESM 脚本文件中使用顶级等待。此外,我需要设置一个布尔标志来指示在顶层成功等待了承诺。

我的意思的一个例子:

let topLevelAwaitEnabled;
try {
    await Promise.resolve(); // replaced with an actual promise
    topLevelAwaitEnabled = true;
} catch (ignored) {
    topLevelAwaitEnabled = false;
}
console.log(topLevelAwaitEnabled);

// carry on with the rest of the application, regardless of success or failure
// at some point, topLevelAwaitEnabled is checked to conditionally execute some code
Run Code Online (Sandbox Code Playgroud)

如果启用了顶级等待支持,则可以很好地成功。但是,如果不支持,这将导致解析期间出现以下错误,并且无法在运行时try/捕获catch

$ node test.js...\test.js:3 …
Run Code Online (Sandbox Code Playgroud)

node.js async-await top-level-await

6
推荐指数
1
解决办法
1385
查看次数

标签 统计

async-await ×1

node.js ×1

top-level-await ×1