I tried using await to make my asynchronous function works like synchronous task, it works for regular function. But this doesn't work on my anonymous function.
So I have this function in my mongoose schema:
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
I tried to validate my hashed password using bcrypt.compare
which requires me to use anonymous function to get the result.
So I tried to compare password using this function:
async (email, password, h) => {
const user = await User.findOne({email: email, isDeleted: false})
if (!user) {
const data = ResponseMessage.error(400, User Not Found')
return h.response(data).code(400)
}
await user.comparePassword(password, (err, isMatch) => {
if (isMatch) {
console.log('TRUE')
return h.response('TRUE')
} else if (!isMatch) {
console.log('FALSE')
return h.response('FALSE')
}
})
console.log('END OF FUNCTION')
return h.response('DEFAULT')
}
Attachment:
I tried to run the server and comparing the password, but it gives me the result of DEFAULT. I tried debugging using console then it shows TRUE/FALSE is showing after END OF FUNCTION. So it prooves my function is working well but my await function didn't wait my task to run another line.
Any help for my this?