您需要才能使用await
返回的承诺。只需包装回调函数,并在出现错误时调用拒绝函数,或者在成功时解析。现在
const saltPasswordAsync = (password, rounds) =>
new Promise((resolve, reject) => {
bcrypt.hash(password, rounds, (err, hash) => {
if (err) reject(err);
else resolve(hash)
});
});
async function doStuff() {
try {
const hash = await saltPasswordAsync('bacon', 8);
console.log('The hash is ', hash);
} catch (err) {
console.error('There was an error ', err);
}
}
doStuff();
可以使用await
等待的承诺,以解决和使用的值。要捕获错误,请使用try/catch语句进行包装。
UPDATE
托马斯指出,你可能不需要包裹回调的承诺,因为bcrypt返回一个承诺,如果你不传递一个回调函数。你可以像这样用bycript.hash
调用替换到saltPasswordAsync
以上:
const hash = await bcrypt.hash('bacon', 8);
console.log('The hash is ', hash);
'saltPassword'是一个承诺,所以你需要使用'then'它来通过回调获得价值。这就是异步代码的工作原理。您不能期望得到函数返回值,该值只有在函数已经返回时才会到达。注意:第二个“await”是无用的。 – trincot
从'return'语句中删除'await'。 –
'async'函数总是返回promise。所以你需要从异步函数中调用'saltPassword'并等待它,或者学习如何使用promise。 – JLRishe