Login Page, want to check for existing users

For my registration page, I want to check for existing users before adding a new user to avoid duplicate usernames. For some reason, after I check if an existing username exists in the database, it does not run any of the code afterwards.

app.post("/register", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  var newuser = false;

  db.query("SELECT * FROM users WHERE username = ?;", [username], (err, result) => {
      
    if (err) {
      res.send({err: err})
    }

    if (result.length == 0) {
      newuser = true;
      console.log(newuser + "one")
    }
  })

    if (newuser) {
    console.log(newuser + "two")
    bcrypt.hash(password, saltRounds, (err, hash) => {
      if (err)
      console.log(err)
    
      db.query(
        "INSERT INTO users (username, password) VALUES (?,?)",
        [username, hash],
        (err, result) => {
        if (err)
          console.log(err);
          }
      )
    })
  }
})

In this example, the only output I get is “trueone” … meaning that it evaluated result.length to 0 and set newuser = true.

Answer

It is because you are not waiting to the result of the first select. You can use async function or move the if(new user) condition into the select callback.