admin管理员组

文章数量:1024582

I have multiple routers in my server, and every time I run my ESLint script, the same error gets thrown for every single one of them. The error in question is this one:

error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises

The code of my routers is like this one:

import { getAllCards } from '../controllers/CardsController';
import express from 'express';
import { isAValidToken } from '../controllers/TokenController';
import { errorCallback } from '../controllers/ErrorController';
const router = express.Router();

router.get('/', isAValidToken, async (req, res) => {
    try {
        const cards = await getAllCards();
        res.json(cards);
    } catch (error: any) {
        errorCallback(error, res);
    }
});

TokenController:

import jwt from 'jsonwebtoken';
import { API_SECRET, API_SECRET_REFRESH, TOKEN_EXP, REFRESH_TOKEN_EXP } from '../constants/constants';
import { Request, Response, NextFunction } from 'express';

async function verifyAnyToken (token: string, secret: string): Promise<unknown> {
    return await new Promise((resolve, reject) => {
        jwt.verify(token, secret, (error) => {
            if (error != null) {
                reject(error);
            } else {
                resolve(token);
            }
        });
    });
}

async function verifyToken (token: string): Promise<unknown> {
    return await verifyAnyToken(token, API_SECRET);
}

export async function getTokenFromRequest (req: Request): Promise<string> {
    const token = req.body.token || req.headers['x-access-token'] || req.headers.authorization || req.params.token;
    return await getNormalizedToken(token);
}

export async function isAValidToken (req: Request, res: Response, next: NextFunction): Promise<void> {
    const token = await getTokenFromRequest(req);
    await verifyToken(token);
    next();
}

Since the error is pointing where the isAValidToken function is called in my router, that seems to be the problem, either with the call itself or with something else that I'm not aware of.

I have multiple routers in my server, and every time I run my ESLint script, the same error gets thrown for every single one of them. The error in question is this one:

error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises

The code of my routers is like this one:

import { getAllCards } from '../controllers/CardsController';
import express from 'express';
import { isAValidToken } from '../controllers/TokenController';
import { errorCallback } from '../controllers/ErrorController';
const router = express.Router();

router.get('/', isAValidToken, async (req, res) => {
    try {
        const cards = await getAllCards();
        res.json(cards);
    } catch (error: any) {
        errorCallback(error, res);
    }
});

TokenController:

import jwt from 'jsonwebtoken';
import { API_SECRET, API_SECRET_REFRESH, TOKEN_EXP, REFRESH_TOKEN_EXP } from '../constants/constants';
import { Request, Response, NextFunction } from 'express';

async function verifyAnyToken (token: string, secret: string): Promise<unknown> {
    return await new Promise((resolve, reject) => {
        jwt.verify(token, secret, (error) => {
            if (error != null) {
                reject(error);
            } else {
                resolve(token);
            }
        });
    });
}

async function verifyToken (token: string): Promise<unknown> {
    return await verifyAnyToken(token, API_SECRET);
}

export async function getTokenFromRequest (req: Request): Promise<string> {
    const token = req.body.token || req.headers['x-access-token'] || req.headers.authorization || req.params.token;
    return await getNormalizedToken(token);
}

export async function isAValidToken (req: Request, res: Response, next: NextFunction): Promise<void> {
    const token = await getTokenFromRequest(req);
    await verifyToken(token);
    next();
}

Since the error is pointing where the isAValidToken function is called in my router, that seems to be the problem, either with the call itself or with something else that I'm not aware of.

Share Improve this question edited Nov 3, 2022 at 19:11 Syed M. Sannan 1,3824 gold badges14 silver badges33 bronze badges asked Nov 3, 2022 at 19:01 Daniel CoronaDaniel Corona 1,2224 gold badges21 silver badges49 bronze badges 1
  • 3 I don't know typescript well but you shouldn't use unknown and you shouldn't await for promise if you return in. – LacticWhale Commented Nov 3, 2022 at 19:10
Add a ment  | 

1 Answer 1

Reset to default 2

async / await is syntactic sugar for a Promise. So by calling async await new Promise() you are effectively resolving a Promise with another Promise. Structure your controller to look more like your router, using a try/catch block without declaring new Promises.

async function verifyAnyToken (token: string) {
 try {
  const decoded = await jwt.verify(token, API_SECRET);
   console.log(decoded);
  } catch(err) {
    console.log(err) 
  }; 
}

export async function getTokenFromRequest (req: Request) {
 try {
  const token = //
  if(token){
    const normalizedToken = await getNormalizedToken(token); // 'return await ...' will just return a promise and not the normalizedToken value
    console.log(normalizedToken);
  } else {
    console.log('No token')
  }}
  catch(err) {
   console.log(err)
  };
}

export async function isAValidToken (req: Request, res: Response, next: Function){
 const token = await getTokenFromRequest(req);
 await verifyAnyToken(token);
 next();
}

The verifyToken() function is redundant. It's just an async function calling another async function from another async function. Which adds unnecessary layers of promises and callbacks.

I have multiple routers in my server, and every time I run my ESLint script, the same error gets thrown for every single one of them. The error in question is this one:

error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises

The code of my routers is like this one:

import { getAllCards } from '../controllers/CardsController';
import express from 'express';
import { isAValidToken } from '../controllers/TokenController';
import { errorCallback } from '../controllers/ErrorController';
const router = express.Router();

router.get('/', isAValidToken, async (req, res) => {
    try {
        const cards = await getAllCards();
        res.json(cards);
    } catch (error: any) {
        errorCallback(error, res);
    }
});

TokenController:

import jwt from 'jsonwebtoken';
import { API_SECRET, API_SECRET_REFRESH, TOKEN_EXP, REFRESH_TOKEN_EXP } from '../constants/constants';
import { Request, Response, NextFunction } from 'express';

async function verifyAnyToken (token: string, secret: string): Promise<unknown> {
    return await new Promise((resolve, reject) => {
        jwt.verify(token, secret, (error) => {
            if (error != null) {
                reject(error);
            } else {
                resolve(token);
            }
        });
    });
}

async function verifyToken (token: string): Promise<unknown> {
    return await verifyAnyToken(token, API_SECRET);
}

export async function getTokenFromRequest (req: Request): Promise<string> {
    const token = req.body.token || req.headers['x-access-token'] || req.headers.authorization || req.params.token;
    return await getNormalizedToken(token);
}

export async function isAValidToken (req: Request, res: Response, next: NextFunction): Promise<void> {
    const token = await getTokenFromRequest(req);
    await verifyToken(token);
    next();
}

Since the error is pointing where the isAValidToken function is called in my router, that seems to be the problem, either with the call itself or with something else that I'm not aware of.

I have multiple routers in my server, and every time I run my ESLint script, the same error gets thrown for every single one of them. The error in question is this one:

error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises

The code of my routers is like this one:

import { getAllCards } from '../controllers/CardsController';
import express from 'express';
import { isAValidToken } from '../controllers/TokenController';
import { errorCallback } from '../controllers/ErrorController';
const router = express.Router();

router.get('/', isAValidToken, async (req, res) => {
    try {
        const cards = await getAllCards();
        res.json(cards);
    } catch (error: any) {
        errorCallback(error, res);
    }
});

TokenController:

import jwt from 'jsonwebtoken';
import { API_SECRET, API_SECRET_REFRESH, TOKEN_EXP, REFRESH_TOKEN_EXP } from '../constants/constants';
import { Request, Response, NextFunction } from 'express';

async function verifyAnyToken (token: string, secret: string): Promise<unknown> {
    return await new Promise((resolve, reject) => {
        jwt.verify(token, secret, (error) => {
            if (error != null) {
                reject(error);
            } else {
                resolve(token);
            }
        });
    });
}

async function verifyToken (token: string): Promise<unknown> {
    return await verifyAnyToken(token, API_SECRET);
}

export async function getTokenFromRequest (req: Request): Promise<string> {
    const token = req.body.token || req.headers['x-access-token'] || req.headers.authorization || req.params.token;
    return await getNormalizedToken(token);
}

export async function isAValidToken (req: Request, res: Response, next: NextFunction): Promise<void> {
    const token = await getTokenFromRequest(req);
    await verifyToken(token);
    next();
}

Since the error is pointing where the isAValidToken function is called in my router, that seems to be the problem, either with the call itself or with something else that I'm not aware of.

Share Improve this question edited Nov 3, 2022 at 19:11 Syed M. Sannan 1,3824 gold badges14 silver badges33 bronze badges asked Nov 3, 2022 at 19:01 Daniel CoronaDaniel Corona 1,2224 gold badges21 silver badges49 bronze badges 1
  • 3 I don't know typescript well but you shouldn't use unknown and you shouldn't await for promise if you return in. – LacticWhale Commented Nov 3, 2022 at 19:10
Add a ment  | 

1 Answer 1

Reset to default 2

async / await is syntactic sugar for a Promise. So by calling async await new Promise() you are effectively resolving a Promise with another Promise. Structure your controller to look more like your router, using a try/catch block without declaring new Promises.

async function verifyAnyToken (token: string) {
 try {
  const decoded = await jwt.verify(token, API_SECRET);
   console.log(decoded);
  } catch(err) {
    console.log(err) 
  }; 
}

export async function getTokenFromRequest (req: Request) {
 try {
  const token = //
  if(token){
    const normalizedToken = await getNormalizedToken(token); // 'return await ...' will just return a promise and not the normalizedToken value
    console.log(normalizedToken);
  } else {
    console.log('No token')
  }}
  catch(err) {
   console.log(err)
  };
}

export async function isAValidToken (req: Request, res: Response, next: Function){
 const token = await getTokenFromRequest(req);
 await verifyAnyToken(token);
 next();
}

The verifyToken() function is redundant. It's just an async function calling another async function from another async function. Which adds unnecessary layers of promises and callbacks.

本文标签: javascriptESLint Promise returned in function argument where a void return was expectedStack Overflow