Mod*_*rmo 8 javascript bcrypt mongoose node.js
继这个问题之后.
我觉得我几乎就在那里,但我对异步的不完全理解阻止了我解决这个问题.我基本上试图使用bcrypt来散列密码并决定分离hashPassword函数,以便我可以在应用程序的其他部分使用它.
hashedPassword 保持返回undefined虽然...
userSchema.pre('save', async function (next) {
let user = this
const password = user.password;
const hashedPassword = await hashPassword(user);
user.password = hashedPassword
next()
})
async function hashPassword (user) {
const password = user.password
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds, function(err, hash) {
if (err) {
return err;
}
return hash
});
return hashedPassword
}
Run Code Online (Sandbox Code Playgroud)
Aka*_*han 29
await等待bcrypt.hash因为bcrypt.hash没有回应许诺.使用以下方法,它包含bcrypt一个promise以便使用await.
async function hashPassword (user) {
const password = user.password
const saltRounds = 10;
const hashedPassword = await new Promise((resolve, reject) => {
bcrypt.hash(password, saltRounds, function(err, hash) {
if (err) reject(err)
resolve(hash)
});
})
return hashedPassword
}
Run Code Online (Sandbox Code Playgroud)
小智 11
默认情况下,bcrypt.hash(password,10)将按承诺返回。请在这里检查
示例:运行代码,
var bcrypt= require('bcrypt');
let password = "12345";
var hashPassword = async function(){
console.log(bcrypt.hash(password,10));
var hashPwd = await bcrypt.hash(password,10);
console.log(hashPwd);
}
hashPassword();
Run Code Online (Sandbox Code Playgroud)
输出:
Promise { <pending> }
$2b$10$8Y5Oj329TeEh8weYpJA6EOE39AA/BXVFOEUn1YOFC.sf1chUi4H8i
Run Code Online (Sandbox Code Playgroud)
当您await在异步函数内部使用时,它将等待直到从诺言中解决。
使用 bcrypt.hashSync() 方法,它是开箱即用的同步。
const hashedPassword = bcrypt.hashSync(password,saltRounds);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11037 次 |
| 最近记录: |