no-return-await
禁止不必要的 return await
此规则报告的一些问题可通过编辑器建议手动修复
此规则在 ESLint v8.46.0 中已弃用,且没有替代方案。该规则的初衷是阻止使用 return await
,以避免额外的微任务。然而,由于 JavaScript 现在以不同的方式处理原生 Promise
,因此不再有额外的微任务。更多技术信息可以在 这个 V8 博客条目 中找到。
¥This rule was deprecated in ESLint v8.46.0 with no replacement. The original intent of this rule was to discourage the use of return await
, to avoid an extra microtask. However, due to the fact that JavaScript now handles native Promise
s differently, there is no longer an extra microtask. More technical information can be found in this V8 blog entry.
在 async function
中使用 return await
将当前函数保留在调用堆栈中,直到正在等待的 Promise 已解决,代价是在解决外部 Promise 之前执行额外的微任务。return await
也可以用在 try/catch 语句中,以从另一个返回 Promise 的函数中捕获错误。
¥Using return await
inside an async function
keeps the current function in the call stack until the Promise that is being awaited has resolved, at the cost of an extra microtask before resolving the outer Promise. return await
can also be used in a try/catch statement to catch errors from another function that returns a Promise.
你可以通过不等待返回值来避免额外的微任务,如果与返回的 Promise 异步抛出错误,则函数的权衡不再是堆栈跟踪的一部分。这会使调试更加困难。
¥You can avoid the extra microtask by not awaiting the return value, with the trade off of the function no longer being a part of the stack trace if an error is thrown asynchronously from the Promise being returned. This can make debugging more difficult.
规则详情
¥Rule Details
此规则旨在防止由于对 async function
的语义缺乏理解而可能导致的常见性能危害。
¥This rule aims to prevent a likely common performance hazard due to a lack of understanding of the semantics of async function
.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-return-await: "error"*/
async function foo() {
return await bar();
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-return-await: "error"*/
async function foo1() {
return bar();
}
async function foo2() {
await bar();
return;
}
// This is essentially the same as `return await bar();`, but the rule checks only `await` in `return` statements
async function foo3() {
const x = await bar();
return x;
}
// In this example the `await` is necessary to be able to catch errors thrown from `bar()`
async function foo4() {
try {
return await bar();
} catch (error) {}
}
何时不使用
¥When Not To Use It
你可能希望关闭此规则有几个原因:
¥There are a few reasons you might want to turn this rule off:
-
如果你想使用
await
来表示一个值是 thenable¥If you want to use
await
to denote a value that is a thenable -
如果你不希望避免
return await
的性能优势¥If you do not want the performance benefit of avoiding
return await
-
如果你希望函数显示在堆栈跟踪中(用于调试目的)
¥If you want the functions to show up in stack traces (useful for debugging purposes)
版本
此规则是在 ESLint v3.10.0 中引入。