Skip to content
← Back to rules

typescript/await-thenable 正确性

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.
An auto-fix is available for this rule.

它做了什么

此规则禁止等待一个非 Thenable 值。

为什么这是个问题?

虽然在 JavaScript 中等待一个非 Promise 类型的值是合法的(它会立即解析),但这种做法可能会让不熟悉该行为的读者感到困惑。此外,这也可能是程序员错误的迹象,例如忘记为返回 Promise 的函数添加括号来调用它。

示例

以下为错误代码示例:

await 12;
await (() => {});

// 非 Promise 值
await Math.random;
await { then() {} };

// 这不是一个 Promise —— 它是一个返回 Promise 的函数
declare const getPromise: () => Promise<string>;
await getPromise;

以下为正确代码示例:

await Promise.resolve('value');
await Promise.reject(new Error());

// Promise 类型的值
await {
  then(onfulfilled, onrejected) {
    onfulfilled('value');
  },
};

// 这是一个 Promise —— 通过调用函数生成
declare const getPromise: () => Promise<string>;
await getPromise();

如何使用

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

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

参考资料