Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
TypeScript/Eslint arroja un error de "Promesa devuelta" en una ruta asíncrona de Express Router

Tengo la siguiente configuración de punto final para restablecer una base de datos después de las ejecuciones de prueba:

 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;

Toda la ruta desde async está subrayada con un error TypeScript-eslint Promise returned in function argument where a void return was expected.

La aplicación funciona perfectamente, pero no estoy seguro de si debería hacer una implementación más segura o simplemente ignorar/deshabilitar Eslint para esta. ¿Alguna idea de lo que está mal con ese código?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Parece que está utilizando la regla de promesas sin uso indebido que establece que no puede devolver Promise<void> en un lugar donde se espera void .

Esto significa que no puede devolver Promise<void> desde su controlador Express porque el tipo de devolución de RequestHandler de la biblioteca especifica que el tipo de devolución debe ser void . Le sugiero que lo cambie para devolver Promise<Response> agregando una simple palabra clave de 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;

La otra opción sería evitar usar async/await :

 router.post('/reset', (_request, response) => { resetDatabase().then(() => response.status(204).send()); });
over 4 years ago · Santiago Trujillo Report

0

Encontré una solución que no implica usar then() y te permite usar la abstracción de async sin que el eslint te maldiga, hay dos soluciones (pero recomiendo más la segunda)

Primera solución: usar "inside async"

Esto es básico usando un asíncrono dentro del vacío como este:

 router.post('/reset', (_request, response) => { (async () => { await resetTestDatabase(); response.status(204).end(); })() });

Segunda solución (recomendada) : "Superposición de tipos"

La segunda opción es que lo uses como asíncrono, como siempre, pero di "oye, TypeScript, nada está mal aquí, jeje" con la palabra clave "as".

 import { RequestHandler } from 'express' router.post('/reset', (async (_request, response) => { await resetTestDatabase(); response.status(204).end(); }) as RequestHandler);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!