Skip to content
← Back to rules

typescript/require-await 严谨

💭 This rule requires type information.
An auto-fix is available for this rule.

它的作用

此规则禁止使用没有 await 表达式的异步函数。

为什么这是不好的?

不使用 await 的异步函数通常是一个错误。它们会不必要地返回 Promise,并且通常可以转换为普通函数。这可以提升性能并使代码更清晰。

示例

以下为 错误 用法的示例:

ts
// 没有 await 的异步函数
async function fetchData() {
  return fetch("/api/data");
}

// 没有 await 的异步箭头函数
const processData = async () => {
  return someData.map((x) => x * 2);
};

// 没有 await 的异步方法
class DataService {
  async getData() {
    return this.data;
  }
}

// 返回 Promise 但未使用 await 的异步函数
async function getPromise() {
  return Promise.resolve("value");
}

以下为 正确 用法的示例:

ts
// 包含 await 的异步函数
async function fetchData() {
  const response = await fetch("/api/data");
  return response.json();
}

// 返回 Promise 的普通函数
function fetchDataSync() {
  return fetch("/api/data");
}

// 条件中包含 await 的异步函数
async function conditionalAwait(condition: boolean) {
  if (condition) {
    return await someAsyncOperation();
  }
  return "default";
}

// 循环中包含 await 的异步函数
async function processItems(items: string[]) {
  const results = [];
  for (const item of items) {
    results.push(await processItem(item));
  }
  return results;
}

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/require-await": "error"
  }
}
bash
oxlint --type-aware --deny typescript/require-await

参考资料