0

I have this code to hash strings and put them in an object list. The hashed strings say 'undefined' in the terminal when I print the object list. When I print the hash from the function, it clearly shows the hash.

What am I missing here?

const bcrypt = require('bcrypt')

const users = []

function hashPassword(password, salt) {
    bcrypt
    .hash(password, salt)
    .then(hash => {
        console.log(hash)
        return hash
    })
    .catch(err => console.log(err.message))
}

const hashedPassword = hashPassword('asdasdasd', 10)

users.push({
    "ID": 01,
    "Name": "Ali Haider",
    "Email": "ali@gmail.com",
    "Password": hashedPassword
})

users.push({
    "ID": 02,
    "Name": "Kumai",
    "Email": "kumai@gmail.com",
    "Password": hashedPassword
})

console.log(users)

Here's the result when I run the code:

PS D:\_Programming\js> node app.js
[
  {
    ID: 1,
    Name: 'Ali Haider',
    Email: 'ali@gmail.com',
    Password: undefined
  },
  {
    ID: 2,
    Name: 'Kumai',
    Email: 'kumai@gmail.com',
    Password: undefined
  }
]
JSON file created.
$2b$10$qEap/oHdL4hrRN9T6Ahr2eZyoIu96Q.23qiHFa0eD1DeN65OhZQB2
Ali
  • 39
  • 4
  • You are not `return`ing from the `hashPassword` function but only from the `.then(…)` callback – Bergi Apr 23 '23 at 20:06
  • I just returned from the hashPassword function and it still did not work. – Ali Apr 24 '23 at 04:32
  • Did you read the answers to the duplicate? You need to return the promise, and then wait for the result when calling the function – Bergi Apr 24 '23 at 05:50

0 Answers0