将密码散列到对象中并接收 Promise { <pending> }

问题描述 投票:0回答:2

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

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': '[email protected]',
    'Password': password
})

console.log(users)

输出:

[
  {
    ID: 0,
    Name: 'Ali',
    Email: '[email protected]',
    Password: Promise { <pending> }
  }
]
Hashing Password: pass
Hashed Password: $2b$10$r52Lu1K.WxOEcAdyeMBV4eR3EPGRXsgJjktJMXFGY5F7a.Q6yoH1C

我一直在输出中收到“Promise { pending }”。我已经研究并尝试使用 async、await,甚至是“then()”。我在这里错过了什么?

javascript bcrypt
2个回答
0
投票

您必须等待

hashPassword
承诺完成。请注意,
async
函数是最后的承诺。

hashPass('pass').then(password => {
users.push({
    'ID': 0,
    'Name': 'Ali',
    'Email': '[email protected]',
    'Password': password
})

console.log(users)

});



0
投票

在将新用户对象推送到 users 数组之前,您需要

await
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': '[email protected]',
        'Password': password
    });

    console.log(users);
}

createUser();
© www.soinside.com 2019 - 2024. All rights reserved.