简体   繁体   English

承诺 {<pending> 在 bcrypt 上

[英]Promise { <pending> } on bcrypt

I am trying to validate a user's password using bcryptjs.我正在尝试使用 bcryptjs 验证用户的密码。 I have this function which returns a Promise, however when I get to bycrypt.hash, all i get is Promise { <pending> } Therefore .then() will not execute on undefined.我有这个返回 Promise 的函数,但是当我到达 bycrypt.hash 时,我得到的只是Promise { <pending> }因此 .then() 不会在 undefined 上执行。 Please help, I've been stuck on this a while请帮忙,我已经被困在这个问题上一段时间了

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();
};

This line will always return a Promise.这一行将始终返回一个 Promise。

console.log(bcrypt.hash(password, this.saltSecret));

You could always do something like this.你总是可以做这样的事情。

return new Promise(async (resolve, reject) => {
    const hash = await bcrypt.hash(password, this.saltSecret);

    if (hash == this.password) {
        return resolve(true);
    }

    return reject();
});

I like to use async-await syntax to handle promises.我喜欢使用 async-await 语法来处理 promise。 It is less confusing.它不那么令人困惑。 and gives the ability of quickly understanding someone else code.并提供快速理解他人代码的能力。

you can make your function an async one.您可以使您的功能成为异步功能。 wait until bcrypt does its job等到 bcrypt 完成它的工作

const password = await bcrypt.hash(password, saltSecret);

However bcrypt library provides a function to compare password and the hash然而 bcrypt 库提供了一个函数来比较密码和哈希

const valid = await bcrypt.compare(password, hashed_pass);

try this尝试这个

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');
  }
};

bcrypt.hash uses a callback, not a promise (that's what the .then is doing) bcrypt.hash使用回调,而不是承诺(这就是.then正在做的事情)

You should use it like so:你应该像这样使用它:

bcrypt.hash(password, this.saltSecret, (err, hash) => {
    ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM