0

I want to do a function that tell me if a user is in my database or not. And I cant get the answer.

I tried to do with a function.

function userExist (user) {
    con.query("SELECT * FROM users WHERE name=?", [user], function(err, result) {
        if(err) throw err;
        if(result)
            return true
        else
        return false
    });
}

I expected true/false but the output is undefined.

O. Jones
  • 103,626
  • 17
  • 118
  • 172

1 Answers1

0

con.query function is asynchronous function(you don't know when it finishes) so userExist function finish even when con.query is not finished yet, to solve that you have to return a promise userExist function and call then to get the desired result like that:

function userExist(user) {
  return new Promise((resolve, reject) => {
    con.query('SELECT * FROM users WHERE name=?', [user], function(
      err,
      result
    ) {
      if (err) reject(false);
      if (result) {
        resolve(true)
      }
      else{
        resolve(false)
      }
    });
  });
}

and when calling userExist call it like that:

userExist(user).then(function(data) {
  if (data) {
    console.log('user is exist');
  }
  else {
    console.log('user is not exist');
  }
}).catch(function(err) {
  console.log(err);
});
Muho
  • 3,188
  • 23
  • 34