sta*_*wed 4 javascript asynchronous bcrypt node.js
我正在使用bcryptjs包来散列和比较密码。
下面使用的方法compareSync
是同步的并返回一个布尔值。它可靠且按预期工作。
let trueOrFalse = bcrypt.compareSync('abcd', '1234');
if(trueOrFalse) {
console.log('hooray, it was true');
} else {
console.log('oops, it was false');
}
Run Code Online (Sandbox Code Playgroud)
下一个示例使用异步compare
方法。我担心,因为这个版本是异步的,如果服务器上有任何延迟,它可能会在确定 的值if/else
之前到达语句。这是一个合理的担忧还是我误解了这种类型的异步函数的本质?bcrypt.compare
res
let trueOrFalse;
bcrypt.compare('abcd', '1234', function(err, res) {
trueOrFalse = res;
}
if(trueOrFalse) {
console.log('hooray, it was true');
} else {
console.log('oops, it was false');
}
Run Code Online (Sandbox Code Playgroud)
异步方法将与您的主程序并行执行,因此您console.log
将在 内部回调函数之前完成bcrypt.compare
。你总是会看到“哎呀,这是假的”。
您可以等待主函数中的实际结果,然后在控制台中显示一些内容。
为了使比较“可等待”,您可以将其包装为Promise
:
function compareAsync(param1, param2) {
return new Promise(function(resolve, reject) {
bcrypt.compare(param1, param2, function(err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
const res = await compareAsync(param1, param2);
console.log(res);
Run Code Online (Sandbox Code Playgroud)
我更喜欢将遗留回调函数包装到 Promises 中,因为它将把应用程序从回调地狱中拯救出来。