---
url: /docs/guide/usage/linter/rules/typescript/promise-function-async.md
---

### 作用

此规则要求任何返回 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 函数
async function fetchData(): Promise<string> {
  const response = await fetch("/api/data");
  return response.text();
}

// Async 方法
class DataService {
  async getData(): Promise<any> {
    const response = await fetch("/api/data");
    return response.json();
  }
}

// Async 箭头函数
const processData = async (): Promise<void> => {
  await someAsyncOperation();
};

// 不返回 Promise 的函数是可以的
function syncFunction(): string {
  return "hello";
}

// 返回类似 Promise 但并非真正 Promise 的函数
function createThenable(): { then: Function } {
  return { then: () => {} };
}
```

## 配置

此规则接受一个具有以下属性的配置对象：

### allowAny

type: `boolean`

default: `true`

是否允许返回 `any` 类型的函数而不要求 `async`。

### allowedPromiseNames

type: `string[]`

default: `[]`

允许在不要求 `async` 的情况下使用的 Promise 类型名称列表。
示例：`["SpecialPromise"]` 表示允许返回 `SpecialPromise` 而不使用 `async`。

### checkArrowFunctions

type: `boolean`

default: `true`

是否检查箭头函数是否缺少 `async` 关键字。

### checkFunctionDeclarations

type: `boolean`

default: `true`

是否检查函数声明是否缺少 `async` 关键字。

### checkFunctionExpressions

type: `boolean`

default: `true`

是否检查函数表达式是否缺少 `async` 关键字。

### checkMethodDeclarations

type: `boolean`

default: `true`

是否检查方法声明是否缺少 `async` 关键字。

## 如何使用

## 版本

此规则于 v1.12.0 中添加。

## 参考
