Skip to content
← Back to rules

promise/no-callback-in-promise Correctness

它的作用

禁止在 Promise.prototype.then()Promise.prototype.catch() 中调用回调函数(cb())。

为什么这不好?

直接在 then()catch() 方法中调用回调,可能会导致 意外行为,例如回调被多次调用。此外, 以这种方式混用回调和 Promise 范式会使代码变得混乱, 且更难维护。

示例

以下是此规则的错误代码示例:

js
function callback(err, data) {
  console.log("回调被调用时传入的参数:", err, data);
  throw new Error("我的错误");
}

Promise.resolve()
  .then(() => callback(null, "data"))
  .catch((err) => callback(err.message, null));

以下是此规则的正确代码示例:

js
Promise.resolve()
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.error(err);
  });

配置

此规则接受一个包含以下属性的配置对象:

callbacks

type: string[]

default: ["callback", "cb", "done", "next"]

要在 Promise thencatch 方法中检查的回调函数名称列表。

exceptions

type: string[]

default: []

允许在 Promise thencatch 方法中使用的回调函数名称列表。

timeoutsErr

type: boolean

default: false

布尔值,表示诸如 setTimeout 之类的超时函数中的回调是否会报错。

如何使用

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

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

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

版本

此规则在 v0.10.0 中加入。

参考资料