gpt4 book ai didi

javascript - 将密码散列到对象中并接收 Promise { }

转载 作者:行者123 更新时间:2023-12-03 07:55:22 27 4
gpt4 key购买 nike

我正在学习散列字符串密码并将它们存储在对象列表中。

const bcrypt = require('bcrypt')

var users = []

async function hashPass(pass)
{
try {
const salt = await bcrypt.genSalt(10)

console.log(`Hashing Password: ${pass}`)

const hashedPass = await bcrypt.hash(pass, salt)

console.log(`Hashed Password: ${hashedPass}`)

return hashedPass

} catch (error) {
console.log(error)
}
}

const password = hashPass('pass')

users.push({
'ID': 0,
'Name': 'Ali',
'Email': 'alihaisul<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c3271795c7b717d7570327f7371" rel="noreferrer noopener nofollow">[email protected]</a>',
'Password': password
})

console.log(users)

输出:

[
{
ID: 0,
Name: 'Ali',
Email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d3dedbdad3dbc1c7de9cdfd7f2d5dfd3dbde9cd1dddf" rel="noreferrer noopener nofollow">[email protected]</a>',
Password: Promise { <pending> }
}
]
Hashing Password: pass
Hashed Password: $2b$10$r52Lu1K.WxOEcAdyeMBV4eR3EPGRXsgJjktJMXFGY5F7a.Q6yoH1C

我不断在输出中收到“Promise {pending}”。我研究并尝试使用 async、await、甚至“then()”。我在这里缺少什么?

最佳答案

由于 hashPass 函数使用 async/await 关键字,它会返回一个 Promise 对象,并且您将其作为输出。

在将新用户对象推送到users数组之前,您需要等待hashPass函数的结果。您可以通过以下方式修改代码来实现此目的:

const bcrypt = require('bcrypt');
var users = [];

async function hashPass(pass) {
try {
const salt = await bcrypt.genSalt(10);
console.log(`Hashing Password: ${pass}`);
const hashedPass = await bcrypt.hash(pass, salt);
console.log(`Hashed Password: ${hashedPass}`);

return hashedPass;
} catch (error) {
console.log(error);
}
}

async function createUser() {
const password = await hashPass('pass');

users.push({
'ID': 0,
'Name': 'Ali',
'Email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c6d6065646d657f79602261694c6b616d6560226f6361" rel="noreferrer noopener nofollow">[email protected]</a>',
'Password': password
});

console.log(users);
}


createUser();

关于javascript - 将密码散列到对象中并接收 Promise { <pending> },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76192369/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com