0

I understand how callbacks work and have successfully created a callback, however I can not get my code to return within the function:

var verifypassword = function(username, password, callback){
      var connection = mysql.createConnection({
           host     : 'hostexample',
           user     : 'jenn',
           password : 'secret',
           database : 'dbexample'
      });
      connection.connect();
      var query = "SELECT _password " +  "from User_Info WHERE username =?";
      connection.query(query, [username], function(err, rows, fields) {
      if (err) return callback(0);
      var string = JSON.stringify(rows);
      var json = JSON.parse(string);
      var correctpassword = json[0]._password;
      return callback(correctpassword);
      });
 }

Then when I call an instance of the verifypassword function:

var verified = verifypassword(username, password, function(correctpassword){
         //console.log(correctpassword);
         return correctpassword;
     });
console.log(correct);
//prints undefined     

If I try to print console.log(correct) in the callback function it will, but it does not return correctpassword.

Any help is appreciated

  • Since `verifypassword` is asynchronous you simply cannot do what you want to do. That's the whole point of having a callback in the first place. If what you wanted to do was possible, you could directly return the desired value from `verifypassword` and didn't need a callback. – Felix Kling Oct 26 '16 at 00:52
  • Thank you! So what you are saying is it is impossible for me (with or without callbacks) to return a value in my database and access it elsewhere (in other functions)? @FelixKling – Jenn Frank Oct 26 '16 at 01:17
  • Not exactly. The callback gives you the possibility to pass the result to functions that need it, e.g. `verifypassword(..., function(result) { otherFunction(result); })`. The linked question should give you more information. – Felix Kling Oct 26 '16 at 01:19

0 Answers0