skip to Main Content

I am learning to hash string passwords and store them in an object list.

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)

OUTPUT:

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

I keep getting the "Promise { pending }" in the output. I’ve researched and tried using async, await, and even the ‘then()’. What am I missing here?

2

Answers


  1. You have to wait for the hashPassword promise to finish. Note that async functions are promises at the end.

    hashPass('pass').then(password => {
    users.push({
        'ID': 0,
        'Name': 'Ali',
        'Email': '[email protected]',
        'Password': password
    })
    
    console.log(users)
    
    });
    
    
    
    Login or Signup to reply.
  2. As hashPass function uses the async/await keywords it returns a Promise object and you are getting that as the output.

    You need to await the result of the hashPass function before pushing the new user object into the users array. Here’s how you can modify your code to do that:

    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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search