no-floating-promises
Require Promise-like statements to be handled appropriately.
"floating" Promise 是在没有设置任何代码来处理它可能抛出的任何错误的情况下创建的。浮动 Promises 可能会导致几个问题,例如操作顺序不正确、忽略 Promise 拒绝等。
¥A "floating" Promise is one that is created without any code set up to handle any errors it might throw. Floating Promises can cause several issues, such as improperly sequenced operations, ignored Promise rejections, and more.
此规则将报告未按以下方式之一处理的 Promise 值语句:
¥This rule will report Promise-valued statements that are not treated in one of the following ways:
-
使用两个参数调用其
.then()
¥Calling its
.then()
with two arguments -
使用一个参数调用其
.catch()
¥Calling its
.catch()
with one argument -
await
ing it -
return
ing it
此规则还会报告何时创建包含 Promise 的数组且未正确处理。解决此问题的主要方法是使用 Promise 并发方法之一创建单个 Promise,然后根据上述过程进行处理。这些方法包括:
¥This rule also reports when an Array containing Promises is created and not properly handled. The main way to resolve this is by using one of the Promise concurrency methods to create a single Promise, then handling that according to the procedure above. These methods include:
-
Promise.all()
-
Promise.allSettled()
-
Promise.any()
-
Promise.race()
no-floating-promises
仅检测明显未处理的 Promise 语句。有关检测向逻辑位置(例如 if 语句)提供 Promises 的代码,请参阅 no-misused-promises
。
¥no-floating-promises
only detects apparently unhandled Promise statements.
See no-misused-promises
for detecting code that provides Promises to logical locations such as if statements.
有关 Promise 错误处理的详细说明,请参阅 在 MDN 上使用承诺(错误处理)。
¥See Using promises (error handling) on MDN for a detailed writeup on Promise error-handling.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-floating-promises": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-floating-promises": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
const promise = new Promise((resolve, reject) => resolve('value'));
promise;
async function returnsPromise() {
return 'value';
}
returnsPromise().then(() => {});
Promise.reject('value').catch();
Promise.reject('value').finally();
[1, 2, 3].map(async x => x + 1);
Open in Playgroundconst promise = new Promise((resolve, reject) => resolve('value'));
await promise;
async function returnsPromise() {
return 'value';
}
void returnsPromise();
returnsPromise().then(
() => {},
() => {},
);
Promise.reject('value').catch(() => {});
await Promise.reject('value').finally(() => {});
await Promise.all([1, 2, 3].map(async x => x + 1));
Open in Playground选项
该规则接受以下选项:
type Options = [
{
/** Type specifiers of functions whose calls are safe to float. */
allowForKnownSafeCalls?: (
| {
from: 'file';
name: [string, ...string[]] | string;
path?: string;
}
| {
from: 'lib';
name: [string, ...string[]] | string;
}
| {
from: 'package';
name: [string, ...string[]] | string;
package: string;
}
| string
)[];
/** Type specifiers that are known to be safe to float. */
allowForKnownSafePromises?: (
| {
from: 'file';
name: [string, ...string[]] | string;
path?: string;
}
| {
from: 'lib';
name: [string, ...string[]] | string;
}
| {
from: 'package';
name: [string, ...string[]] | string;
package: string;
}
| string
)[];
/** Whether to check all "Thenable"s, not just the built-in Promise type. */
checkThenables?: boolean;
/** Whether to ignore async IIFEs (Immediately Invoked Function Expressions). */
ignoreIIFE?: boolean;
/** Whether to ignore `void` expressions. */
ignoreVoid?: boolean;
},
];
const defaultOptions: Options = [
{
allowForKnownSafeCalls: [],
allowForKnownSafePromises: [],
checkThenables: false,
ignoreIIFE: false,
ignoreVoid: true,
},
];
¥Options
checkThenables
Whether to check all "Thenable"s, not just the built-in Promise type. Default: false
.
"Thenable" 值是一个具有 then
方法的对象,例如 Promise
。其他 Thenable 包括 TypeScript 的内置 PromiseLike
接口和任何恰好具有 .then()
的自定义对象。
¥A "Thenable" value is an object which has a then
method, such as a Promise
.
Other Thenables include TypeScript's built-in PromiseLike
interface and any custom object that happens to have a .then()
.
checkThenables
选项触发 no-floating-promises
还考虑满足 Thenable 形状(采用两个回调参数的 .then()
方法)的所有值,而不仅仅是 Promises。如果你的代码使用较旧的 Promise
polyfill 而不是原生 Promise
类,这可能很有用。
¥The checkThenables
option triggers no-floating-promises
to also consider all values that satisfy the Thenable shape (a .then()
method that takes two callback parameters), not just Promises.
This can be useful if your code works with older Promise
polyfills instead of the native Promise
class.
- ❌ Incorrect
- ✅ Correct
declare function createPromiseLike(): PromiseLike<string>;
createPromiseLike();
interface MyThenable {
then(onFulfilled: () => void, onRejected: () => void): MyThenable;
}
declare function createMyThenable(): MyThenable;
createMyThenable();
Open in Playgrounddeclare function createPromiseLike(): PromiseLike<string>;
await createPromiseLike();
interface MyThenable {
then(onFulfilled: () => void, onRejected: () => void): MyThenable;
}
declare function createMyThenable(): MyThenable;
await createMyThenable();
Open in PlaygroundignoreVoid
Whether to ignore void
expressions. Default: true
.
将 void
运算符 放在 Promise 前面是一种方便的方式,可以明确标记该 Promise 为故意不等待。
¥Placing the void
operator in front of a Promise can be a convenient way to explicitly mark that Promise as intentionally not awaited.
使 Promise 无效不会处理它或更改运行时行为。结果被忽略,就像使用 ESLint 禁用注释 禁用规则一样。此类 Promise 拒绝仍将无法处理。
¥Voiding a Promise doesn't handle it or change the runtime behavior. The outcome is just ignored, like disabling the rule with an ESLint disable comment. Such Promise rejections will still be unhandled.
带有 { ignoreVoid: true }
的此规则的正确代码示例:
¥Examples of correct code for this rule with { ignoreVoid: true }
:
async function returnsPromise() {
return 'value';
}
void returnsPromise();
void Promise.reject('value');
Open in Playground当此选项设置为 true
时,如果你使用 no-void
,则应打开 allowAsStatement
选项。
¥When this option is set to true
, if you are using no-void
, you should turn on the allowAsStatement
option.
ignoreIIFE
Whether to ignore async IIFEs (Immediately Invoked Function Expressions). Default: false
.
带有 { ignoreIIFE: true }
的此规则的正确代码示例:
¥Examples of correct code for this rule with { ignoreIIFE: true }
:
await (async function () {
await res(1);
})();
(async function () {
await res(1);
})();
Open in PlaygroundallowForKnownSafePromises
Type specifiers that are known to be safe to float. Default: []
.
例如,你可能需要在库的 API 返回 Promises 的情况下执行此操作,而这些 Promises 的拒绝由库安全处理。
¥For example, you may need to do this in the case of libraries whose APIs return Promises whose rejections are safely handled by the library.
此选项采用共享 TypeOrValueSpecifier
格式。
¥This option takes the shared TypeOrValueSpecifier
format.
带有此规则的代码示例:
¥Examples of code for this rule with:
{
"allowForKnownSafePromises": [
{ "from": "file", "name": "SafePromise" },
{ "from": "lib", "name": "PromiseLike" },
{ "from": "package", "name": "Bar", "package": "bar-lib" }
]
}
- ❌ Incorrect
- ✅ Correct
let promise: Promise<number> = Promise.resolve(2);
promise;
function returnsPromise(): Promise<number> {
return Promise.resolve(42);
}
returnsPromise();
Open in Playground// promises can be marked as safe by using branded types
type SafePromise = Promise<number> & { __linterBrands?: string };
let promise: SafePromise = Promise.resolve(2);
promise;
function returnsSafePromise(): SafePromise {
return Promise.resolve(42);
}
returnsSafePromise();
Open in PlaygroundallowForKnownSafeCalls
Type specifiers of functions whose calls are safe to float. Default: []
.
例如,在库的 API 可能被调用而不处理结果 Promises 的情况下,你可能需要执行此操作。
¥For example, you may need to do this in the case of libraries whose APIs may be called without handling the resultant Promises.
此选项采用共享 TypeOrValueSpecifier
格式。
¥This option takes the shared TypeOrValueSpecifier
format.
带有此规则的代码示例:
¥Examples of code for this rule with:
{
"allowForKnownSafeCalls": [
{ "from": "file", "name": "safe", "path": "input.ts" }
]
}
- ❌ Incorrect
- ✅ Correct
declare function unsafe(...args: unknown[]): Promise<void>;
unsafe('...', () => {});
Open in Playgrounddeclare function safe(...args: unknown[]): Promise<void>;
safe('...', () => {});
Open in Playground何时不使用它
¥When Not To Use It
在设置了许多浮动 Promise 的大型现有项目上,可能很难启用此规则。或者,如果你不担心浮动或误用 Promise 导致的崩溃(例如,如果你注册了全局未处理的 Promise 处理程序),那么在某些情况下,不使用此规则可能是安全的。你可以考虑在这些特定情况下使用 void
和/或 ESLint 禁用注释,而不是完全禁用此规则。
¥This rule can be difficult to enable on large existing projects that set up many floating Promises.
Alternately, if you're not worried about crashes from floating or misused Promises -such as if you have global unhandled Promise handlers registered- then in some cases it may be safe to not use this rule.
You might consider using void
s and/or ESLint disable comments for those specific situations instead of completely disabling this rule.
相关
¥Related To
进一步阅读
¥Further Reading
-
"使用 Promise" MDN 文档。特别注意 Promise 拒绝事件 和 组合 的部分。
¥"Using Promises" MDN documentation. Note especially the sections on Promise rejection events and Composition.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.
'## 资源'