Skip to content
← Back to rules

oxc/no-async-endpoint-handlers Suspicious

它的作用

禁止将 async 函数用作 Express 端点处理器。

这为什么不好?

在 v5 之前,Express 不会自动将处理器函数中的 Promise 拒绝交给应用程序的错误处理器。你必须改为显式地将被拒绝的 promise 传递给 next()

js
const app = express();
app.get("/", (req, res, next) => {
  new Promise((resolve, reject) => {
    return User.findById(req.params.id);
  })
    .then((user) => res.json(user))
    .catch(next);
});

如果不这样做,你的服务器将因未处理的 promise 拒绝而崩溃。

js
const app = express();
app.get("/", async (req, res) => {
  // 如果 User.findById 拒绝,服务器将崩溃
  const user = await User.findById(req.params.id);
  res.json(user);
});

更多信息请参阅 Express 的错误处理指南

示例

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

js
const app = express();
app.get("/", async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);
});

const router = express.Router();
router.use(async (req, res, next) => {
  const user = await User.findById(req.params.id);
  req.user = user;
  next();
});

const createUser = async (req, res) => {
  const user = await User.create(req.body);
  res.json(user);
};
app.post("/user", createUser);

// 导入的异步处理器不会被检测到,因为每个
// 文件都是独立检查的。这不会触发该规则,但仍然
// 违反了规则,并且 _will_ 导致服务器崩溃。
const asyncHandler = require("./asyncHandler");
app.get("/async", asyncHandler);

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

js
const app = express();
// 不是 async
app.use((req, res, next) => {
  req.receivedAt = Date.now();
});

app.get("/", (req, res, next) => {
  fs.readFile("/file-does-not-exist", (err, data) => {
    if (err) {
      next(err); // 将错误传递给 Express。
    } else {
      res.send(data);
    }
  });
});

const asyncHandler = async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);
};
app.get("/user", (req, res, next) => asyncHandler(req, res).catch(next));

配置

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

allowedNames

type: string[]

default: []

允许为 async 的名称数组。

如何使用

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

json
{
  "rules": {
    "oxc/no-async-endpoint-handlers": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "oxc/no-async-endpoint-handlers": "error",
  },
});
bash
oxlint --deny oxc/no-async-endpoint-handlers

版本

此规则在 v0.9.2 中添加。

参考资料