What should I do with function of registration to fix @typescript-eslint/no-misused-promises. The one way I found how to fix this problem is write by eslint.
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": false
}
]
But I'd like to solve this problem as so as eslint requires. Any ideas?
import PromiseRouter from "express-promise-router";
import { login, registration } from './authController';
const router = PromiseRouter();
> ESLint: Promise returned in function argument where a void return was
> expected.(@typescript-eslint/no-misused-promises)
router.post('/registration', registration);
Here is full function of registration
export async function registration(req: TreqBodyReg, res: Response): Promise<void> {
try {
const { email, password } = req.body;
const candidate = await ModelUser.findOne({ email }) as TuserFromDB;
if (candidate) {
res.status(400).json({ message: `There is user with email ${email}` });
return;
}
const hashPassword = bcrypt.hashSync(password, 7);
const user = new ModelUser({ email, password: hashPassword });
await user.save();
res.status(200).json({ message: `The user by email ${email} was successfully registered` });
} catch (err: unknown) {
res.status(400).json({ message: err });
}
};
It's roundabout, but I solved the problem this way.
async function registerUser(req: TreqBodyReg, res: Response): Promise<void> {
const { email, password } = req.body;
const candidate = await ModelUser.findOne({ email }) as TuserFromDB;
if (candidate) {
res.status(400).json({ message: `There is user with email ${email}` });
return;
}
const hashPassword = bcrypt.hashSync(password, 7);
const user = new ModelUser({ email, password: hashPassword });
await user.save();
res.status(200).json({ message: `The user by email ${email} was successfully registered` });
}
export function registration(req: TreqBodyReg, res: Response): void {
registerUser(req, res).catch((err: unknown) => {
res.status(400).json({ message: err });
});
}
I've encountered the same problem using the default Router and solved it by doing this:
router.get("/", function(request: Request, response: Response): void {
void (async function(): Promise<void> {
// do your asychronous work here
response.json(/* put your payload here */);
})();
});
I admit that I'm not fond of the extra boilerplate, but it's the best answer I've found so far.
The (async function(): Promise<void> {...})(); part is just an asyncronous self-invoking function (note the extra () at the end). The void in front of it drops the return type so that ESLint knows you really intend to ignore the returned promise. Without it, you get a "no-floating-promises" error. Of course, that means you are taking responsibility for using try-catch internally to deal with errors...
So, the end result with this approach is that the extra boilerplate allows you to to use async/await in the default Express Router.