require-await
禁止没有 await 表达式的异步函数
此规则报告的一些问题可通过编辑器 建议 手动修复
JavaScript 中的异步函数在两个重要方面与其他函数不同:
🌐 Asynchronous functions in JavaScript behave differently than other functions in two important ways:
- 返回值总是
Promise。 - 你可以在它们里面使用
await操作符。
使用异步函数的主要原因通常是使用 await 操作符,例如这样:
🌐 The primary reason to use asynchronous functions is typically to use the await operator, such as this:
async function fetchData(processDataItem) {
const response = await fetch(DATA_URL);
const data = await response.json();
return data.map(processDataItem);
}
不使用 await 的异步函数可能不需要是异步函数,并且可能是重构的无意结果。
🌐 Asynchronous functions that don’t use await might not need to be asynchronous functions and could be the unintentional result of refactoring.
注意:此规则忽略异步生成器函数。这是因为生成器是 yield 而不是返回一个值,并且异步生成器可能会 yield 另一个异步生成器的所有值,而实际上从不需要使用 await。
🌐 Note: this rule ignores async generator functions. This is because generators yield rather than return a value and async generators might yield all the values of another async generator without ever actually needing to use await.
规则详情
🌐 Rule Details
此规则警告没有 await 表达式的异步函数。
🌐 This rule warns async functions which have no await expression.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint require-await: "error"*/
async function foo() {
doSomething();
}
bar(async () => {
doSomething();
});
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint require-await: "error"*/
async function foo() {
await doSomething();
}
bar(async () => {
await doSomething();
});
function baz() {
doSomething();
}
bar(() => {
doSomething();
});
async function resourceManagement() {
await using resource = getAsyncResource();
resource.use();
}
// Allow empty functions.
async function noop() {}
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 When Not To Use It
异步函数被设计用于与 Promise 一起工作,这样抛出错误将导致调用 Promise 的拒绝处理程序(例如 catch())。例如:
🌐 Asynchronous functions are designed to work with promises such that throwing an error will cause a promise’s rejection handler (such as catch()) to be called. For example:
async function fail() {
throw new Error("Failure!");
}
fail().catch(error => {
console.log(error.message);
});
在这种情况下,fail() 函数会抛出一个错误,该错误旨在由稍后分配的 catch() 处理程序捕获。将 fail() 函数转换为同步函数将需要将对 fail() 的调用重构为使用 try-catch 语句,而不是使用 promise。
🌐 In this case, the fail() function throws an error that is intended to be caught by the catch() handler assigned later. Converting the fail() function into a synchronous function would require the call to fail() to be refactored to use a try-catch statement instead of a promise.
如果你为此目的在异步函数内部抛出错误,那么你可能需要禁用此规则。
🌐 If you are throwing an error inside of an asynchronous function for this purpose, then you may want to disable this rule.
相关规则
版本
此规则是在 ESLint v3.11.0 中引入。