Search code examples
node.jstypescriptexpressnode-mysql

Express async route logging undefined after await


I am writing an Express endpoint in Typescript to update a user's password in the database, but having some trouble with multiple queries/synchronous code.

My problem is right now I am trying to await the return of a function but it doesn't seem to be awaiting.

My route looks like this:

router.put("/:userId", validateUser, async (req: any, res: Response) => {
    const result: any = await updatePassword(req.body.password, req.body.confirmPassword, req.params.userId);
    console.log(result) //LOGS UNDEFINED????
    if (result.status !== 200) res.status(result.status).send({ message: result.message, code: result.code });
    res.send("Success!");
});

and that updatePassword function looks like this:

const updatePassword = async (password: string, confirmPassword: string, userId: string) => {
    if (password !== confirmPassword) {
        return { status: 409,  message: Errors.mismatchingPasswordMessage, code: Errors.mismatchingPasswordCode };
    }

    const hashedPassword = bcrypt.hashSync(password, 10);
    //update the password in the DB
    pool.query("UPDATE users SET password = ? WHERE userId = ?", [hashedPassword, userId], (err: MysqlError, result: any) => {
        if (err) {
            console.log(err);
            return { status: 500,  message: err.message, code: err.code };
        }
        if (result.changedRows !== 1) {
            return { status: 500,  message: "Password could not be updated!" };
        }

        return { status: 200 };
    });
}

Why is this the route not correctly awaiting the result of updatePassword??

Thanks in advance for any help.


Solution

  • The problem is, you're mixing async/await and callback style in this part

     pool.query("UPDATE users SET password = ? WHERE userId = ?", [hashedPassword, userId], (err: MysqlError, result: any) => {
            if (err) {
                console.log(err);
                return { status: 500,  message: err.message, code: err.code };
            }
            if (result.changedRows !== 1) {
                return { status: 500,  message: "Password could not be updated!" };
            }
    
            return { status: 200 };
        });
    

    The function updatePassword jumps directly to the next line after this block, which is nothing. So it returns undefined.

    You need to replace this block with async/await code. Something like :

    try {
           const result = await pool.query("UPDATE users SET password = ? WHERE userId = ?", [hashedPassword, userId]);
            
            if (result.changedRows !== 1) {
                return { status: 500,  message: "Password could not be updated!" };
            }
    
            return { status: 200 };
    }
    catch (err){
    
           console.log(err);
           return { status: 500,  message: err.message, code: err.code };
            
    }