typescript/promise-function-async 限制
它做了什么
此规则要求任何返回 Promise 的函数或方法都必须标记为 async。
为什么这是不好的?
返回 Promise 的函数通常应标记为 async,以清晰地表明其异步特性,并允许在其中使用 await。这可以提高代码可读性,并帮助防止与 Promise 处理相关的常见错误。
示例
此规则的 错误 代码示例:
ts
// 返回 Promise 但未标记为 async
function fetchData(): Promise<string> {
return fetch("/api/data").then((res) => res.text());
}
// 返回 Promise 但未标记为 async
class DataService {
getData(): Promise<any> {
return fetch("/api/data").then((res) => res.json());
}
}
// 返回 Promise 但未标记为 async
const processData = (): Promise<void> => {
return Promise.resolve();
};此规则的 正确 代码示例:
ts
// 异步函数
async function fetchData(): Promise<string> {
const response = await fetch("/api/data");
return response.text();
}
// 异步方法
class DataService {
async getData(): Promise<any> {
const response = await fetch("/api/data");
return response.json();
}
}
// 异步箭头函数
const processData = async (): Promise<void> => {
await someAsyncOperation();
};
// 不返回 Promise 的函数是允许的
function syncFunction(): string {
return "hello";
}
// 返回类 Promise 但不是实际 Promise 的函数
function createThenable(): { then: Function } {
return { then: () => {} };
}配置
此规则接受一个配置对象,包含以下属性:
allowAny
type: boolean
默认值: true
是否允许返回 any 类型的函数而不强制要求使用 async。
allowedPromiseNames
type: string[]
默认值: []
允许不使用 async 即可返回的 Promise 类型名称列表。 例如:["SpecialPromise"] 表示允许返回 SpecialPromise 类型的函数不使用 async。
checkArrowFunctions
type: boolean
默认值: true
是否检查箭头函数中缺少 async 关键字的情况。
checkFunctionDeclarations
type: boolean
默认值: true
是否检查函数声明中缺少 async 关键字的情况。
checkFunctionExpressions
type: boolean
默认值: true
是否检查函数表达式中缺少 async 关键字的情况。
checkMethodDeclarations
type: boolean
默认值: true
是否检查方法声明中缺少 async 关键字的情况。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/promise-function-async": "error"
}
}bash
oxlint --type-aware --deny typescript/promise-function-async