eslint/require-await Pedantic
它的作用
禁止没有 await 表达式的 async 函数。
注意
此规则的准确性不如具备类型感知的 typescript/require-await 规则。如果使用类型感知 规则,请始终优先使用该规则而不是本规则。
为什么这不好?
JavaScript 中的异步函数在两个重要方面与其他函数的行为不同:
- 返回值始终是
Promise。 - 你可以在其中使用
await操作符。
使用异步函数的主要原因通常是使用 await 操作符,例如:
js
async function fetchData(processDataItem) {
const response = await fetch(DATA_URL);
const data = await response.json();
return data.map(processDataItem);
}不使用 await 的异步函数可能并不需要是 异步函数,且可能是重构时无意造成的结果。
注意:此规则会忽略 async 生成器函数。这是因为 生成器产生值而不是返回值,而 async 生成器可能会 生成另一个 async 生成器的所有值,却从未真正需要 使用 await。
示例
以下是此规则的错误代码示例:
js
async function foo() {
doSomething();
}以下是此规则的正确代码示例:
js
async function foo() {
await doSomething();
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"require-await": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"require-await": "error",
},
});bash
oxlint --deny require-await版本
此规则在 v0.4.2 中添加。
