Bcrypt.compare() Is Asynchronous, Does That Necessarily Mean That Delays Are Certain To Happen?
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 tru
Solution 1:
Asynchronous method will be executed in parallel with your main program, so your console.log
will be done before the callback function inside bcrypt.compare
. You will see always 'oops, it was false'.
You can wait for the real result in your main function and then show something in console.
To make comparison 'waitable' you can wrap it into Promise
:
functioncompareAsync(param1, param2) {
returnnewPromise(function(resolve, reject) {
bcrypt.compare(param1, param2, function(err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
const res = awaitcompareAsync(param1, param2);
console.log(res);
I prefer to wrap legacy callback functions into Promises because it will save an app from a callback hell.
Solution 2:
The Node.js runtime will surely run the synchronous code (the if-else statements) before you get the result from the async computation. You are guaranteed that the computation is completed only in the callback function:
bcrypt.compare('abcd', '1234', function(err, res) {
// make your checks hereif (res) {
// ...
}
})
Post a Comment for "Bcrypt.compare() Is Asynchronous, Does That Necessarily Mean That Delays Are Certain To Happen?"