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.