TypeScript/Eslint 在 Express Router 异步路由上抛出“承诺返回”错误

问题描述

我有以下端点设置来在测试运行后重置数据库

import { getConnection } from 'typeorm';
import express from 'express';
const router = express.Router();

const resetDatabase = async (): Promise<void> => {
  const connection = getConnection();
  await connection.dropDatabase();
  await connection.synchronize();
};

// typescript-eslint throws an error in the following route:
router.post('/reset',async (_request,response) => {
  await resetTestDatabase();
  response.status(204).end();
});

export default router;

async 以来的整个路线都带有下划线,并带有 typescript-eslint 错误 Promise returned in function argument where a void return was expected.

该应用程序运行良好,但我不确定我是否应该进行更安全的实现,或者只是为此忽略/禁用 Eslint。知道这段代码有什么问题吗?

解决方法

您似乎正在使用 no-misused-promises 规则,该规则规定您不能在需要 Promise<void> 的地方返回 void

这意味着您不能从 Express 处理程序返回 Promise<void>,因为库中 RequestHandler 的返回类型指定返回类型应为 void。我建议您通过添加一个简单的 Promise<Response> 关键字将其更改为返回 return

import { getConnection } from 'typeorm';
import express from 'express';
const router = express.Router();

const resetDatabase = async (): Promise<void> => {
  const connection = getConnection();
  await connection.dropDatabase();
  await connection.synchronize();
};

// typescript-eslint throws an error in the following route:
router.post('/reset',async (_request,response) => {
  await resetTestDatabase();
  return response.status(204).send();  // <----- return added here
});

export default router;

另一种选择是避免使用 async/await

router.post('/reset',(_request,response) => {
  resetDatabase().then(() => response.status(204).send());
});