2
Hello, I am having a problem adding a custom error in an array of errors, in the validation of a form with nodejs. I’ve tried to change my approach but I haven’t found a solution,
//PARTE 1
let errors = []
db.query('SELECT * FROM Users WHERE email = ?', [emailregister], (err, result) => {
if (result.length > 0) {
errors.push ({ err_email_msg: 'Email já cadastrado' })
}
})
//PARTE 2
if (errors.length == 0) {
db.query('INSERT INTO Users (`name`, `email`, `password`, `celnumber`, `genre`, `birthdate`) VALUES (?, ?, ?, ?, ?, ?)',
[name, emailregister, registerpwd, celnumber, genreOption, datanascimento], (err, rows, fields) => {
if (err)
res.send(err)
else
res.send('Register OK!')
})
} else {
res.render('register', {
errors,
primeironome,
sobrenome,
emailregister,
registerpwd,
confirmpwd,
celnumber,
genreOption,
datanascimento,
title: 'Registre-se'
})
}
turns out, it’s entering the if of part 2, with errors.length == 0 being TRUE, even going through the errors.push of part 1.
With a.log() console right after the errors.push within the if of part 1, the error array is printed in the correct way, but if you place the.log console after the db.query of part 1, an empty array is printed. Because this errors.push() in part 1 does not work properly?
The call
db.query
is asynchronous.– Augusto Vasques
They are different codes, different purpose and different environments, but you are having the same problem that user had: https://answall.com/a/450720/137387
– Augusto Vasques
knew db.query is asynchronous but was not able to handle it. After a few readings I managed to resolve it. Thanks for the comments.
– Daniel Campos