I am using bcryptpare
to compare the passwords:
UserSchema.methodsparePasswords = async function (canditatePassword) {
const isMatching = await bcryptpare(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?
I am using bcryptpare
to compare the passwords:
UserSchema.methodsparePasswords = async function (canditatePassword) {
const isMatching = await bcryptpare(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?
2 Answers
Reset to default 2There 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,
bcryptpare
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 useawait
, thenisMatching
is a promise and not a boolean. That promise is returned. This means the promise returned by theasync
function is resolved with the promiseisMatching
(it is locked-in to it). That in turn means that the promise returned by theasync
function resolves to the boolean of interest, which is also the result whenawait
is used.Note that if you choose to omit
await
, you can also omitasync
. That latter keyword is only useful for functions that need to executeawait
.
As other answers explain, await
is not necessary indeed and won't affect the result of comparePasswords
. Currently isMatching
variable has no purpose, so it could be reduced to:
UserSchema.methodsparePasswords = async function (canditatePassword) {
return bcryptpare(canditatePassword, this.password)
}
And async
could be discarded too because the function unconditionally returns a promise.
Debugging is a scenario that makes it desirable to have a variable and await
that are optional in general:
UserSchema.methodsparePasswords = async function (canditatePassword) {
const isMatching = await bcryptpare(canditatePassword, this.password)
debugger;
return isMatching
}
This way isMatching
boolean value can be easily observed at the breakpoint regardless of how comparePasswords
is used.