array.push() inside mysql.query callback (nodejs)

Asked

Viewed 122 times

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.

  • 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

  • 1

    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.

2 answers

1

I managed to settle with:

db.connect(async () => { 
const result = await db.promise().query('SELECT * FROM Users WHERE email = ?', [emailregister]) 
if (result[0].length) { 
errors.push({ err_email_msg: 'Email já cadastrado' }) 
} ...

Thus, I was able to conditional the error array normally in the same block

if (errors.length == 0){ 
db.query('INSERT INTO Users ...

I don’t know if it’s the most elegant way, but I solved my problem. Thanks for the comments.

1

The problem is that db.query is asynchronous and the callback is called after the rest of the code (the if/else) happen. That is, the array errors not yet have mysql data.

Two solutions:

a) Usa async/await as you did:

// PARTE 1
db.connect(async () => { 
    const result = await db.promise().query('SELECT * FROM Users WHERE email = ?', [emailregister]) 
    if (result[0].length) { 
        errors.push({ err_email_msg: 'Email já cadastrado' }) 
    }
});

// PARTE 2
... etc

b) Places the rest of the logic inside the callback:

// 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'
    })
  }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.