0

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 ?

Malaury Boudon
  • 656
  • 1
  • 8
  • 18
  • `Since JS is asynchronous` - no - some functions are, but JS isn't – Jaromanda X Sep 05 '19 at 01:24
  • thanks for the correction. Here it's the case, I verified with console.log :/ – Malaury Boudon Sep 05 '19 at 01:44
  • no, JS is not asynchronous in this case either ... it never is ... in the case of `connection.query(queryString, (err, rows) => {`, the callback is called back asynchronously when the query "completes" ... but this JS code is still not "asynchronous" – Jaromanda X Sep 05 '19 at 01:47
  • ok, do you know a way to put ```conncetion.query``` in sychronous mode? or to wait it result before to do something else ? – Malaury Boudon Sep 05 '19 at 02:26

0 Answers0