0

Relevant posts already exist but I couldn't figure out how to apply the principles to my situation.

I need the function to return the returnVal as modified within the callback (which obviously doesn't work - returns false every time).

Any ideas?

function login(user){
  var returnVal = false;
  User.findOne({username: user.username}, function (err, res){
    res.comparePassword(user.password, function(err, isMatch) {
      if (err) throw err;
      if(isMatch){
        returnVal = true;
      }
    });
  });
  return returnVal;
}

Thank you!

  • See http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – guest271314 Apr 23 '17 at 03:10
  • Stop trying to solve the wrong problem. Instead of trying to return the value you need (which is being loaded asynchronously), pass the function that needs the value as an argument to `function login(user, callback){...}` and use it as a callback like `callback(returnVal)` inside of `function(err, isMatch) {...}` at the end. – Patrick Roberts Apr 23 '17 at 03:14

1 Answers1

0
function login(user){
  var returnVal = false;
  // vvv-- This gets executed asynchronously --vvv
  User.findOne({username: user.username}, function (err, res){
    res.comparePassword(user.password, function(err, isMatch) {
      if (err) throw err;
      if(isMatch){
        returnVal = true;
      }
    });
  });
  return returnVal;
}

So what you need to do is either use promises (preferred) or pass in a callback which gets executed when the asynchronous process is done.

Since I'm not familiar with promises, here an example with a callback:

function login(user, callback) {
  // This gets executed asynchronously
  User.findOne({username: user.username}, function (err, res) {
    res.comparePassword(user.password, function(err, isMatch) {
      if (err) throw err;
      // Invoke the callback
      callback(isMatch);
    });
  });
}

Usage:

login({user: '...', pass: 'secret'}, function(returnVal) {
  console.log('login() returned ' + returnVal)
})

Side note: promises are preferred because of so-called callback hell.

You can read more on the topic here.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marco
  • 7,007
  • 2
  • 19
  • 49