2017-10-07 176 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

相關問題