2017-10-07 163 views
0

我期待创建一个简单的帮助函数,它返回给定密码的哈希使用bcrypt但每次我打电话的功能,它解决了Promises { <pending> }我做错了什么?Resolving Promise <pending>

const saltPassword = async (password) => { 
    const newHash = await bcrypt.hash(password, saltRounds, (err, hash) => { 
     if (err) return err; 
     return hash; 
    }); 
    return await newHash; 
} 

欢呼

+0

'saltPassword'是一个承诺,所以你需要使用'then'它来通过回调获得价值。这就是异步代码的工作原理。您不能期望得到函数返回值,该值只有在函数已经返回时才会到达。注意:第二个“await”是无用的。 – trincot

+0

从'return'语句中删除'await'。 –

+0

'async'函数总是返回promise。所以你需要从异步函数中调用'saltPassword'并等待它,或者学习如何使用promise。 – JLRishe

回答

2

你应该做这样的事情

const saltPassword = async (password) => { 
const newHash = await bcrypt.hash(password,  saltRounds, (err, hash) => { 
    if (err) return err; 
    return hash; 
    }); 
return newHash; // no need to await here 
} 

// Usage 

const pwd = await saltPassword; 
0

您需要才能使用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); 
+0

@Thomas谢谢!我更新了我的答案。我从来没有使用过bcrypt,OP也没有提及他们正在使用哪个实现,所以我会留下两个选项。 – styfle

相关问题