Skip to main content

no-misused-promises

禁止在未设计用于处理 Promises 的地方使用 Promises.

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

此规则禁止向逻辑位置提供 Promise,例如 TypeScript 编译器允许但未正确处理的位置的 if 语句。这些情况通常是由于缺少 await 关键字或只是对异步函数处理/等待方式的误解而发生的。

¥This rule forbids providing Promises to logical locations such as if statements in places where the TypeScript compiler allows them but they are not handled properly. These situations can often arise due to a missing await keyword or just a misunderstanding of the way async functions are handled/awaited.

提示

no-misused-promises 仅检测向不正确的逻辑位置提供 Promises 的代码。有关检测未处理的 Promise 语句,请参阅 no-floating-promises

¥no-misused-promises only detects code that provides Promises to incorrect logical locations. See no-floating-promises for detecting unhandled Promise statements.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-misused-promises": "error"
}
});

在线运行试试这个规则 ↗

选项

该规则接受以下选项:

type Options = [
{
/** 是否在向条件语句提供 Promise 时发出警告。 */
checksConditionals?: boolean;
/** 当 `...` 扩展 `Promise` 时是否发出警告。 */
checksSpreads?: boolean;
/** 是否在从类型为返回 `void` 的函数返回 Promise 时发出警告。 */
checksVoidReturn?: /**
* 是否在从类型为返回 `void` 的函数返回 Promise 时发出警告。
* 是否禁用检查所有异步函数。
*/
| boolean
/** 哪些形式的函数可能已禁用检查。 */
| {
/** 禁用检查作为参数传递的异步函数,其中参数类型预期为返回 `void` 的函数。 */
arguments?: boolean;
/** 禁用检查作为 JSX 属性传递的异步函数,该函数预期为返回 `void` 的函数。 */
attributes?: boolean;
/** 禁用检查在扩展或实现另一种类型的类型中的异步方法,该方法预期该方法返回 `void`。 */
inheritedMethods?: boolean;
/** 禁用检查作为对象属性传递的异步函数,该函数预期为返回 `void` 的函数。 */
properties?: boolean;
/** 禁用检查在返回类型为返回 `void` 的函数的函数中返回的异步函数。 */
returns?: boolean;
/** 禁用检查用作变量的异步函数,该变量的返回类型为返回 `void` 的函数。 */
variables?: boolean;
};
},
];

const defaultOptions: Options = [
{ checksConditionals: true, checksSpreads: true, checksVoidReturn: true },
];

¥Options

checksConditionals

是否在向条件语句提供 Promise 时发出警告。 Default: true.

如果你不想检查条件,你可以使用 "checksConditionals": false 配置规则:

¥If you don't want to check conditionals, you can configure the rule with "checksConditionals": false:

{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksConditionals": false
}
]
}

这样做可防止规则查看类似 if (somePromise) 的代码。

¥Doing so prevents the rule from looking at code like if (somePromise).

checksVoidReturn

是否在从类型为返回 void 的函数返回 Promise 时发出警告。 Default: true.

同样,如果你不想在预期返回 void 的情况下检查返回 Promise 的函数,你的配置将如下所示:

¥Likewise, if you don't want to check functions that return promises where a void return is expected, your configuration will look like this:

{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": false
}
]
}

你可以通过提供禁用特定检查的对象来禁用 checksVoidReturn 选项的选择性部分。例如,如果你不介意将 () => Promise<void> 传递给 () => void 参数或 JSX 属性可能会导致浮动未处理的 Promise:

¥You can disable selective parts of the checksVoidReturn option by providing an object that disables specific checks. For example, if you don't mind that passing a () => Promise<void> to a () => void parameter or JSX attribute can lead to a floating unhandled Promise:

{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": {
"arguments": false,
"attributes": false
}
}
]
}

支持以下子选项:

¥The following sub-options are supported:

arguments

禁用检查作为参数传递的异步函数,其中参数类型预期为返回 void 的函数。

¥Disables checking an asynchronous function passed as argument where the parameter type expects a function that returns void.

attributes

禁用检查作为 JSX 属性传递的异步函数,该函数预期为返回 void 的函数。

¥Disables checking an asynchronous function passed as a JSX attribute expected to be a function that returns void.

inheritedMethods

禁用检查在扩展或实现另一种类型的类型中的异步方法,该方法预期该方法返回 void

¥Disables checking an asynchronous method in a type that extends or implements another type expecting that method to return void.

注意

目前,no-misused-promises 仅针对扩展/实现的类型检查命名方法:也就是说,调用/构造/索引签名将被忽略。TypeScript 中的调用签名不需要彼此一致,并且构造签名首先不能是 async。索引签名检查可能会在将来实现。

¥For now, no-misused-promises only checks named methods against extended/implemented types: that is, call/construct/index signatures are ignored. Call signatures are not required in TypeScript to be consistent with one another, and construct signatures cannot be async in the first place. Index signature checking may be implemented in the future.

properties

禁用检查作为对象属性传递的异步函数,该函数预期为返回 void 的函数。

¥Disables checking an asynchronous function passed as an object property expected to be a function that returns void.

returns

禁用检查在返回类型为返回 void 的函数的函数中返回的异步函数。

¥Disables checking an asynchronous function returned in a function whose return type is a function that returns void.

variables

禁用检查用作变量的异步函数,该变量的返回类型为返回 void 的函数。

¥Disables checking an asynchronous function used as a variable whose return type is a function that returns void.

checksSpreads

... 扩展 Promise 时是否发出警告。 Default: true.

如果你不想检查对象分布,可以添加以下配置:

¥If you don't want to check object spreads, you can add this configuration:

{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksSpreads": false
}
]
}

示例

¥Examples

checksConditionals

带有 checksConditionals: true 的此规则的代码示例:

¥Examples of code for this rule with checksConditionals: true:

const promise = Promise.resolve('value');

if (promise) {
// Do something
}

const val = promise ? 123 : 456;

[1, 2, 3].filter(() => promise);

while (promise) {
// Do something
}
Open in Playground

checksVoidReturn

带有 checksVoidReturn: true 的此规则的代码示例:

¥Examples of code for this rule with checksVoidReturn: true:

[1, 2, 3].forEach(async value => {
await fetch(`/${value}`);
});

new Promise<void>(async (resolve, reject) => {
await fetch('/');
resolve();
});

document.addEventListener('click', async () => {
console.log('synchronous call');
await fetch('/');
console.log('synchronous call');
});

interface MySyncInterface {
setThing(): void;
}
class MyClass implements MySyncInterface {
async setThing(): Promise<void> {
this.thing = await fetchThing();
}
}
Open in Playground

checksSpreads

带有 checksSpreads: true 的此规则的代码示例:

¥Examples of code for this rule with checksSpreads: true:

const getData = () => fetch('/');

console.log({ foo: 42, ...getData() });

const awaitData = async () => {
await fetch('/');
};

console.log({ foo: 42, ...awaitData() });
Open in Playground

何时不使用它

¥When Not To Use It

在设置了许多滥用 Promise 的大型现有项目中,很难启用此规则。或者,如果你不担心浮动或误用 Promise 导致的崩溃(例如,如果你注册了全局未处理的 Promise 处理程序),那么在某些情况下,不使用此规则可能是安全的。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥This rule can be difficult to enable on large existing projects that set up many misused 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 ESLint disable comments for those specific situations instead of completely disabling this rule.

进一步阅读

¥Further Reading

相关


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.

¥Related To

资源