2

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': 'alihaisul.me@gmail.com',
    'Password': password
})

console.log(users)

OUTPUT:

[
  {
    ID: 0,
    Name: 'Ali',
    Email: 'alihaisul.me@gmail.com',
    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?

Ali
  • 39
  • 4
  • An `async function` always return a `Promise`. `await` it to retrieve the actual return value (i.e. `hashedPass`). – InSync May 07 '23 at 05:49
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – user3840170 May 07 '23 at 07:50

2 Answers2

4

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': 'alihaisul.me@gmail.com',
    'Password': password
  });

  console.log(users);
}


createUser();
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    Thank you for the explanation using the createUser function. I understood better this way. – Ali May 07 '23 at 06:24
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': 'alihaisul.me@gmail.com',
    'Password': password
})

console.log(users)

});


Erez Shlomo
  • 2,124
  • 2
  • 14
  • 27