'How to deal with async functions in express js router

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;
    
    
    
    
    
        const getUser = async (req: Request, res: Response, next: 
          NextFunction): Promise<any> => {
        try {
            const { id } = req.params;
            if (!id) {
                let response = formatErrorResponse({ error: true, statusCode: 400, errorMessage: 'Missing id in params' });
                return res.status(400).json(response);
            }
            let user = await User.findById({_id: id});
            let objRes = { error: false, statusCode: 200, message: 'User was found', data: user };
            return res.status(200).json(objRes);
        } catch (error) {
            console.log('error in controller /user', error)
            next(error);
        }
    }
    
    export {
        getUser
    }
    
    
    
    
         const validateJWT = async (req: Request, res: Response, next: NextFunction): Promise<any> => {
        const token = req.header('x-token');
        console.log(req)
        if (!token) {
            const err = formatErrorResponse({ error: true, statusCode: 401, errorMessage: 'Missing header x-token' });
            return res.status(401).json(err);
        } 
        try { 
            await verifyToken(token);
            next(); 
        } catch (error) {
            const err = formatErrorResponse({error: true, statusCode: 401, errorMessage: 'Invalid token, athorization denied', errorContent: error});
            return res.status(400).json(err);
        }
    }


Solution 1:[1]

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(...));

Solution 2:[2]

I suggest something like the below.

router.use(validateJWT)

router.get('/users/:id', (req, res, next) => {
    getUser(req.params.id)
        .then(res.json)
        .catch(next);
});

In the docs, I could see an async middleware example http://expressjs.com/en/guide/writing-middleware.html#mw-fig.

I could not find an async handler example. I recall that back in the day, express didn't support async handler. Hence, I used .then inside the handler. You need to double-check if you can use them nowadays.

In the express docs is also an example like the below. It makes working with async handler more convenient in some regard. As you can wrap all your async handler with this wrapper.

const wrap = fn => (...args) => fn(...args).catch(args[2]);

router.get('/users/:id', wrap(getUser));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2