I am using bcrypt.compare
to compare the passwords:
UserSchema.methods.comparePasswords = async function (canditatePassword) {
const isMatching = await bcrypt.compare(canditatePassword, this.password)
return isMatching
}
Based on the docs:
Asynchronously compares the given data against the given hash
But VSCode underlines the await
keyword and shows a warning:
'await' has no effect on the type of this expression
Indeed, when I apply the quick fix and remove the await
keyword, everything still works fine. Can anyone explain me, why is the await
not needed here?
There are two things playing a role here:
The VS Code warning: this warning is expected when the function returns a value that is not a promise, but in your case it does return a promise. However, bcrypt.compare
has two signatures. When you provide a third argument to it (a callback), the function does not return a promise, and the warning would be warranted. I suppose that VS Code doesn't detect this nuance.
Why it also works without await
: In case you don't use await
, then isMatching
is a promise and not a boolean. That promise is returned. This means the promise returned by the async
function is resolved with the promise isMatching
(it is locked-in to it). That in turn means that the promise returned by the async
function resolves to the boolean of interest, which is also the result when await
is used.
Note that if you choose to omit await
, you can also omit async
. That latter keyword is only useful for functions that need to execute await
.