我正在使用bcryptjs包对密码进行哈希和比较。
下面使用的comparesync
方法是同步的,并返回一个布尔值。它是可靠的和工作的预期。
let trueOrFalse = bcrypt.compareSync('abcd', '1234');
if(trueOrFalse) {
console.log('hooray, it was true');
} else {
console.log('oops, it was false');
}
下一个示例使用异步compare
方法。我担心的是,由于此版本是异步的,如果服务器上有任何延迟,它可能会在bcrypt.compare
确定res
的值之前到达if/else
语句。这是一个合理的担心,还是我误解了这种类型的异步函数的性质?
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');
}
异步方法将与您的主程序并行执行,因此您的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);
我更喜欢将遗留的回调函数封装到承诺中,因为这将使应用程序免于回调地狱。
node.js运行时肯定会在得到异步计算的结果之前运行同步代码(if-else语句)。可以保证计算只在回调函数中完成:
bcrypt.compare('abcd', '1234', function(err, res) {
// make your checks here
if (res) {
// ...
}
})