I encountered a problem when dealing with queries' error handling for a MySQL database in NodeJS : I searched a bit about callbacks in JavaScript and async functions but I cannot figure out how am I suppose to get the correct error message that I want in a type of situation, here it is :
auth.post('/register', (req, res) => {
const body = req.body;
console.log('POST register');
const user = {email: body.email, password: body.password, name: body.name, firstname: body.firstname};
my_db.query('INSERT INTO user SET ?', user, (err, result) => {
if (err) {
console.log("ERROR");
is_err = false;
}
})
is_err = true;
if (!is_err)
res.json({"msg" : "user already exists"});
else
res.json({"token": "Token of the newly registered user"});
})
Typically I want that the json formatted message {"msg" : "user already exists"} is sent as a response when a user already exists. I tried booleans, numbers, async functions but seems like I am doing this terribly. And I cannot do res.json()
inside the query ! How am I suppose to do it ?