'Node js I can't return a query using mysql

When I try to return a query, we get an undefined object, I don't know why, I need to return a value to the main function but always is undefined, I need to return that information to validate a user in the database, when I do the same function in main was working, but when I try to separate the functions can't work.

class login{

    validateUser(user, pass){
        const connection = require ('./db');
        let datos = connection.query('SELECT * FROM login WHERE usuario = ?', [user], async(error, results)=>{
            if (results.length == 0 || pass != results[0].password){
                return null;
            }
            else{
                return results;
            }
        });
    }
}

module.exports = login

I need to return values in this function to validate login:

app.post('/auth', async (req, res)=>{
    const user = req.body.user;
    const pass = req.body.pass;

    
    const log = new login();

    const response = log.validateUser(user, pass);
    console.log(response);
    

    if(!response){
        res.render('login',{
            alert:true,
            alertTitle: "Error",
            alertMessage: "Usuario y/o Contraseña incorrecta",
            alertIcon : "error",
            showConfirmButton: true,
            timer: null,
            ruta: 'login'
        });
    }
    else{
        req.session.loggedin=true;
        req.session.name = response[0].usuario;
        res.render('login',{
            alert:true,
            alertTitle: "Conexión exitosa",
            alertMessage: "!Login exitoso¡",
            alertIcon : "success",
            showConfirmButton: false,
            timer: 2000,
            ruta: ''
        });
    }
});


Solution 1:[1]

I think the problem is in these lines

1. const response = log.validateUser(user, pass);
2. console.log(response);

This code is running Asynchronously so line 2 is running before the completion of line 1 that is why you are getting the response as undefined.

I suggest you use Async await for this if your database client supports it or make your custom Promise such that you code do

//note the await keyword before log
1. const response = await log.validateUser(user, pass);
2. console.log(response);

This will make sure that line 2 or any code below only executes once you have fetched and returned your data properly

P.S: Above fix won't work until unless your fix the implementation of validateUser to support Async Await via Promise

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 Zulfiqar Ali