unicorn/prefer-top-level-await Pedantic
它的作用
优先使用顶层 await,而不是顶层 Promise 和 async 函数调用。
为什么这不好?
顶层 await 更易读,并且可以防止未处理的拒绝。
示例
以下是此规则的错误代码示例:
js
(async () => {
await run();
})();
run().catch((error) => {
console.error(error);
});以下是此规则的正确代码示例:
js
await run();
try {
await run();
} catch (error) {
console.error(error);
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"unicorn/prefer-top-level-await": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/prefer-top-level-await": "error",
},
});bash
oxlint --deny unicorn/prefer-top-level-await版本
此规则于 v1.20.0 中添加。
