0

Say we have the following if statement

.
.
if (!user.comparePassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
    }
.
.

where comparePassword(password) is a function to check if the user input password is identical to the one in the database.., and it's in another module being defined as follows:

userSchema.methods.comparePassword = function (password) {
let match = false;

bcrypt.compare(password, this.password)
.then(function (isMatch) {
  if(isMatch){
    match = true;
  }
})
.catch(function (err) {
  // handle error
});
return match;
};

The problem is in I/O.., where one could easily see the if statement depends on a function comparePassword(password) that could finish execution before the promises inside it bcrypt.compare() finishes execution.., which means I get match most of the time false even if it should technically be true. the compare function of bcrypt runs an expensive operation, so how do I get the result of comparison in time without blocking code-execution ?

Profess Physics
  • 317
  • 4
  • 11
  • 1
    You cannot *get* the result. You have to wait, and only continue with the rest of your code when it's available. – Bergi Sep 20 '17 at 00:46
  • but wouldn't that be horrible for other users' requests ? – Profess Physics Sep 20 '17 at 00:47
  • I did not say you'd have to block for waiting. That's the magic of asynchrony/concurrency: other stuff can happen while you are waiting. – Bergi Sep 20 '17 at 00:48
  • 1
    You cannot. The `return` needs to happen immediately, it cannot block until the result is available. You can however return the promise from the function, and then use `user.comparePassword(password).then(function(match) { if (match) { … } else {…} });` – Bergi Sep 20 '17 at 00:56
  • Got it thank you for helping me out. – Profess Physics Sep 20 '17 at 00:57

0 Answers0