使用"bcrypt"的密码散列方法返回未定义


import bcrypt from 'bcrypt';
export default class Hash {
 static hashPassword (password: any): string {
   let hashed: string;
    bcrypt.hash(password, 10, function(err, hash) {
      if (err) console.log(err);
      else {
        hashed = hash;
      }
    });
    return hashed;
   }

}

此功能每次都返回未定义

当您 return hashed时,哈希功能尚未完成。

您想在回调函数本身中处理您的哈希密码,或者正如Aluan指出的那样处理异步函数。

做到这一点的一种方法是使用诺言

export default class Hash {
    return new Promise((resolve, reject) => {
        static hashPassword (password: any): string {
       let hashed: string;
        bcrypt.hash(password, 10, function(err, hash) {
          if (err) reject(err);
          else {
            resolve(hash);
          }
        });
       }
    })
}

然后,当您想致电哈希时,将其称为Promise

Hash.then(hashed => {
    console.log(hashed)
}).catch(err => {
    console.log(err)
})

最新更新