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

password hashing methond using "bcrypt" returns undefined

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


}

this function returns undefined everytime

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

        });
       }
    })

}

然后当你想调用hash的时候,把它当作promise来调用

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