Skip to content
← Back to rules

promise/always-return 可疑

它做了什么

要求在每个 then() 中都返回值,以创建清晰且可复用的 Promise 链。 我们还允许在 then() 内部抛出异常,这本质上等同于返回 Promise.reject()

为什么这是有问题的?

中断的 Promise 链。 在第一个 then() 回调中,调用了一个函数但未返回。 这会导致链中的下一个 then() 立即执行,而无需等待被调用的函数完成。

示例

此规则的 错误 代码示例:

javascript
myPromise.then(function (val) {});
myPromise.then(() => {
  doSomething();
});
myPromise.then((b) => {
  if (b) {
    return "yes";
  } else {
    forgotToReturn();
  }
});

此规则的 正确 代码示例:

javascript
myPromise.then((val) => val * 2);
myPromise.then(function (val) {
  return val * 2;
});
myPromise.then(doSomething); // 可能是任意形式
myPromise.then((b) => {
  if (b) {
    return "yes";
  } else {
    return "no";
  }
});

配置

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

ignoreAssignmentVariable

type: string[]

default: ["globalThis"]

你可以通过传入 { ignoreAssignmentVariable: [] } 作为该规则的选项,并提供一个变量名列表,使得当一个 Promise 链中的最后一个 then() 回调对全局变量进行赋值时不会发出警告。默认值为 ["globalThis"]

javascript
/* promise/always-return: ["error", { ignoreAssignmentVariable: ["globalThis"] }] */

// OK
promise.then((x) => {
  globalThis = x;
});

promise.then((x) => {
  globalThis.x = x;
});

// OK
promise.then((x) => {
  globalThis.x.y = x;
});

// NG
promise.then((x) => {
  anyOtherVariable = x;
});

// NG
promise.then((x) => {
  anyOtherVariable.x = x;
});

// NG
promise.then((x) => {
  x();
});

ignoreLastCallback

type: boolean

default: false

你可以通过传入 { ignoreLastCallback: true } 作为该规则的选项,使得当一个 Promise 链中的最后一个 then() 回调没有 return 时不会发出警告。默认值为 false

javascript
// OK
promise.then((x) => {
  console.log(x);
});
// OK
void promise.then((x) => {
  console.log(x);
});
// OK
await promise.then((x) => {
  console.log(x);
});

promise
  // NG
  .then((x) => {
    console.log(x);
  })
  // OK
  .then((x) => {
    console.log(x);
  });

// NG
const v = promise.then((x) => {
  console.log(x);
});
// NG
const v = await promise.then((x) => {
  console.log(x);
});
function foo() {
  // NG
  return promise.then((x) => {
    console.log(x);
  });
}

如何使用

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

json
{
  "plugins": ["promise"],
  "rules": {
    "promise/always-return": "error"
  }
}
bash
oxlint --deny promise/always-return --promise-plugin

参考资料