我正在尝试使用bcryptjs验证用户的密码。我有这个函数,它返回一个Promise,但是当我到达bycrypt.hash时,我得到的是Promise { <pending> },因此.then()不会在未定义的上执行。请帮帮忙,我被困在这件事上有一阵子了
userSchema.methods.verifyPassword = function (password, err, next) {
const saltSecret = this.saltSecret;
const a = async function(resolve, reject) {
console.log('hi4')
console.log('this.saltSecret2', saltSecret);
console.log(password);
const hashed_pass = await bcrypt.hash(password, saltSecret);
console.log('hash', hashed_pass);
const valid = await bcrypt.compare(password, hashed_pass);
if(valid){
console.log('GOOD');
}
};
a();
};发布于 2020-01-31 10:35:00
我喜欢使用async-await语法来处理promises。这就不那么令人困惑了。并提供快速理解其他人代码的能力。
你可以让你的函数成为异步函数。等到bcrypt完成它的工作
const password = await bcrypt.hash(password, saltSecret);但是,bcrypt库提供了一个比较密码和散列的函数
const valid = await bcrypt.compare(password, hashed_pass);尝尝这个
async function(resolve, reject) {
console.log('hi4')
console.log(this.saltSecret);
console.log(password);
const hashed_pass = await bcrypt.hash(password, saltSecret);
console.log('hash', hashed_pass);
const valid = await bcrypt.compare(password, hashed_pass);
if(valid){
console.log('GOOD');
}
};发布于 2020-01-31 10:29:04
此行将始终返回Promise。
console.log(bcrypt.hash(password, this.saltSecret));你总是可以做这样的事情。
return new Promise(async (resolve, reject) => {
const hash = await bcrypt.hash(password, this.saltSecret);
if (hash == this.password) {
return resolve(true);
}
return reject();
});发布于 2020-01-31 10:27:46
bcrypt.hash使用回调,而不是promise (这就是.then正在做的事情)
你应该这样使用它:
bcrypt.hash(password, this.saltSecret, (err, hash) => {
...
});https://stackoverflow.com/questions/59997071
复制相似问题