require-await

禁止没有 await 表达式的异步函数

💡 hasSuggestions

此规则报告的一些问题可通过编辑器建议手动修复

JavaScript 中的异步函数在两个重要方面与其他函数不同:

¥Asynchronous functions in JavaScript behave differently than other functions in two important ways:

  1. 返回值始终为 Promise

    ¥The return value is always a Promise.

  2. 你可以在其中使用 await 运算符。

    ¥You can use the await operator inside of them.

使用异步函数的主要原因通常是使用 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.

注意:此规则忽略异步生成器函数。这是因为生成器产生而不是返回值,并且异步生成器可能会产生另一个异步生成器的所有值,而实际上不需要使用等待。

¥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();
});

// Allow empty functions.
async function noop() {}

何时不使用

¥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 中引入。

资源

ESLint 中文网
粤ICP备13048890号