I would like to have a synchronized query in JavaScript to check it query's response before doing anything else. I can not insert the rest of my code into the processing of the query because I would like to return a status code when an error appears.
I tried to put the rest of code into the query treatment but I got this message on my terminal : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
router.post('/login', (req, res) => {
    const { error } = validate(req.body);
    if(error) return res.status(400).send(error.details[0].message);
    const queryString = `SELECT * FROM user_admin WHERE email = '${req.body.email}' AND password = '${req.body.password}'`;
    connection.query(queryString, (err, rows) => {
        console.log(rows);
        if(err) throw err;
        else if(rows.length != 0){
            res.status(200).json({
                'token': jwtUtils.generateTokenForUser(rows[0].iduser_admin)
            });
        }
        return res.status(404).send('ERROR 404 : Password and (or) email are false.');
    });
});
This is my actual code :
router.post('/login', (req, res) => {
    const { error } = validate(req.body);
    if(error) return res.status(400).send(error.details[0].message);
    var iduser_admin = findUserId();
    if(iduser_admin === 0 || iduser_admin === undefined) return res.status(404).send('ERROR 404 : Password and (or) email are false.');
    res.status(200).json({
        'token': jwtUtils.generateTokenForUser(iduser_admin)
    });
});
function findUserId(){
    const queryString = `SELECT * FROM user_admin WHERE email = '${req.body.email}' AND password = '${req.body.password}'`;
    connection.query(queryString, (err, rows) => {
        console.log(rows);
        if(err) throw err;
        else if(rows.length != 0){
            return rows[0].iduser_admin;
        }
        return 0;
    });
}
Since JS is asynchronous, my variable isadmin_user is not updated before the next if. So, it's always status (400).
I don't find how to use .then() or callback in this case. (I'm new with JS)
Because if I put the rest of code inside an other function called by my query treatment the problems with res.status will appear, no ? Could you help me ?
