I'm using the bcryptjs package to hash and compare passwords.
The compareSync
method used below is synchronous and returns a boolean. It is reliable and works as expected.
let trueOrFalse = bcrypt.compareSync('abcd', '1234');
if(trueOrFalse) {
console.log('hooray, it was true');
} else {
console.log('oops, it was false');
}
The next example uses the asynchronous compare
method. I'm concerned that because this version is async if there is any delay on the server it may get to the if/else
statement before bcrypt.compare
has determined the value of res
. Is this a valid concern or am I misunderstanding the nature of this type of async function?
let trueOrFalse;
bcrypt.compare('abcd', '1234', function(err, res) {
trueOrFalse = res;
}
if(trueOrFalse) {
console.log('hooray, it was true');
} else {
console.log('oops, it was false');
}