Home > database >  How to deal with async functions in express js router
How to deal with async functions in express js router

Time:04-18

There is a lint error, that basically says that we cannot return Promises in places where a void is expected, the message is clear, but how to fix it without lying to the linter by using any or (as any), both functions [validateJWT, getUser] are async functions

It looks pretty basic, but I do not know how to fix it in an easy way. thanks!

import { Router } from 'express';
import { getUser } from '../controllers/userController';
import { validateJWT } from '../middlewares/validateJWT';

const router = Router();

router.get('/user', validateJWT, getUser);

export default router;

CodePudding user response:

You need to change your implementation of the function to work like this:

router.get('/user', (req, res) => {
  validateJWT(req, res);
  getUser(req, res);
});

Since express.Router instances expect the route as a string for the first parameter which you have as "/user". And a second parameter which is a callback.

Inside that callback you can call your functions.

Assuming you need validateJWT to finish running before getUser you could do something like this:

validateJWT(...).then((...) => getUser(...));

CodePudding user response:

Express doesnt await handlers. So they cant be async.

One of your functions is also a middleware, you probably want to use it.

I suggest something like this:

router.use((req, res, next) => {
    validateJWT(req, res).then(() => {
        next();
    }).catch(() => {
        res.status(401).json({
            message: 'Unauthorized'
        });
    });
})

router.get('/user', (req, res, next) => {
    getUser(req, res).then((user) => {
        res.json(user);
    }).catch((err) => {
        res.status(500).json({
            message: err.message
        });
    });
});
  • Related