Javascript 信息输出早于验证
解释如何同步实现它以及它是如何工作的Javascript 信息输出早于验证,javascript,node.js,Javascript,Node.js,解释如何同步实现它以及它是如何工作的 let user = req.body; if (user.user_password) { bcrypt.hash(user.user_password, config.salt.saltRounds, (err, hash) => { user.user_password = hash; console.log(user) }); } console.log(user) Bcrypt故意放慢
let user = req.body;
if (user.user_password) {
bcrypt.hash(user.user_password, config.salt.saltRounds, (err, hash) => {
user.user_password = hash;
console.log(user)
});
}
console.log(user)
Bcrypt故意放慢速度,以防止更快的硬件轻松破解哈希,因此它异步执行,以避免在该点锁定应用程序 检查此链接: 无论如何,以下解决方案将同步“查看”
async function foo() {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
}
foo();
console.log(this.password);
Bcrypt故意放慢速度,以防止更快的硬件轻松破解哈希,因此它异步执行,以避免在该点锁定应用程序 检查此链接: 无论如何,以下解决方案将同步“查看”
async function foo() {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
}
foo();
console.log(this.password);
为什么是异步的?你的代码是异步的。在您的代码中有一个回调函数,该函数在
散列完成后运行。当您的hash
正在“计算”时,您的其他代码将运行,而不是停止程序的其余部分,从而执行底部的console.log
。然后,当您的哈希
完成时,它将调用回调函数,从而执行第二个控制台。log
您对函数使用的是承诺还是异步等待?为什么是异步的?您的代码是异步的。在您的代码中有一个回调函数,该函数在散列完成后运行。当您的hash
正在“计算”时,您的其他代码将运行,而不是停止程序的其余部分,从而执行底部的console.log
。然后当你的散列
完成时,它将调用回调函数,从而执行你的第二个控制台。log
你是在为你的函数使用承诺还是异步等待?