0

I'm trying to create an asynchronous password check, but I don't seem to be able to get it to work (I have a feeling my still sketchy knowledge of async and callbacks is to blame).

The method:

ProSchema.methods.correctPassword = function(password, next) {
  console.log('FIRE 1');
  bcrypt.compare(password, this.local.password, function(err, result) {
    if (err) {
      console.log('FIRE 2');
      return next(err);
    }
    console.log('FIRE 3: '+result);
    return result;
  });
};

Assuming there's no error then the console log reads:

FIRE 1
FIRE 3: true

Happy days. However I'm using this method in my passport config:

var pass = pro.correctPassword(password);
if (!pass) {
   console.log(pass);
   return done(null, false, "Wrong password.");
}

The console log embedded in that statement always outputs as undefined.

Now I think I understand why - because when that if statement executes bcrypt is still checking the password (is that correct?), so I tried the following:

pro.correctPassword(password, function(err, result) {
   console.log(result);
})

i.e. I added a callback function to the method call, the idea being that I can drop the if (!pass) in there and it will only be executed when the response is returned. But… that doesn't seem to work, at all. That console log never even fires.

So I'm a bit stuck. If anyone could help explain to this lost soul what's wrong with my approach I'd greatly appreciate it! As I say I'm still trying to get into the async/callback mindset, and I think I'm getting there… but clearly have a little way to go.

Nathan Hornby
  • 1,423
  • 16
  • 32
  • You know what @Blakes Seven - I think you're right - however I've been staring at the answers for a while now and I'm still struggling to take anything from them to apply to my code. Async is clearly something that needs drumming in for some folks (myself included…). But I'm thinking it has to do with `ProSchema.methods.correctPassword` being a synchronous function - am I on the right track? – Nathan Hornby Jul 28 '15 at 15:26
  • I'm either getting closer or adding red herrings, but thinking about it I can't use an async function for checking the password can I? Because it's inherently blocking code, because I need the response before I can do anything else? – Nathan Hornby Jul 28 '15 at 15:29
  • 1
    It means you are calling `return something` and you cannot do that. You work with values "inside" the callback. Which is what the answers there say. – Blakes Seven Jul 28 '15 at 15:30
  • OK that's definitely clicked a piece into place in my brain - if I wanted something to happen from within the callback, I'd need to be calling another function, with the response from the callback as a parameter? (or just executing code directly within the callback) - but no returns, because that implies the other code is waiting for its response, which it's not, because it's async. – Nathan Hornby Jul 28 '15 at 15:33

0 Answers0