I have a web formulary from where i extract data. The unique field should be the email, but if i repeat the email my formulary breaks and throws error, i don't know how to stop my formulary to break, i just want a error.push("reenter your email"), withouth connecting again to the db using npm start. I am looking for a validation or smth, i am beginner into node.js and working with js
connection.query(
"SELECT * FROM `employees` WHERE `email`= ?",
[employee.email],
function (err, row) {
if (err) throw err;
else {
if (row && row.length) {
error.push("Email already exists!"); //this does nothing
return console.log("Email is existing already!");
}
}
}
);
if(error.length === 0){
// insert data in the table
}
else {
res.status(400).send(error);
console.log("Error");
}
I want error.push("Email already exists!"); to modify my error array so it won't enter in the first if(error.length === 0)
CodePudding user response:
connection.query
is an asynchronous function. So error.push
happens after your if
.
Possible solutions -
- Move the further code into the callback function
- Create a Promise and resolve it in the function, aka use the
async/await
system. Example function:
const executeQuery = (con, query, params = null) => {
return new Promise((resolve, reject) => {
con.query(query, params, (err, res) => {
if (err) {
reject(err);
return
}
resolve(res);
});
})
};
You can run this, and you can say await executeQuery(con,query,param)
and proceed from there.