Skip to content
← Back to rules

promise/prefer-catch 样式

🚧 An auto-fix is planned for this rule, but not implemented at this time.

作用 ​

优先使用 catch 而不是 then(a, b) 和 then(null, b)。此规则不允许在 then 调用的第二个参数中传入参数来处理 promise 错误。

为什么这不好? ​

带有两个参数的 then 调用会让人更难识别其中存在 catch 错误处理器。另一个在 then 调用中使用第二个参数的问题是,promise 错误处理的顺序不够明显。

例如,乍一看似乎 prom.then(fn1, fn2) 等同于 prom.then(fn1).catch(fn2)。然而它们并不等价。实际上,prom.catch(fn2).then(fn1) 才是等价的。此类混淆正是优先使用显式的 catch 调用,而不是向 then 调用的第二个参数传入参数的一个很好的理由。

示例 ​

此规则的错误代码示例:

js
prom.then(fn1, fn2);

prom.then(null, fn2);

此规则的正确代码示例:

js
prom.catch(fn2).then(fn1);

prom.catch(fn2);

如何使用 ​

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["promise"],
  "rules": {
    "promise/prefer-catch": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["promise"],
  rules: {
    "promise/prefer-catch": "error",
  },
});
bash
oxlint --deny promise/prefer-catch --promise-plugin

版本 ​

此规则添加于 v0.15.14。

参考资料 ​