Bcrypt Returing [Object Promise] or Promise { <pending> } after Hashing a Code

Viewed 419

I am creating an account signup system for a React app. I am having an issue when trying to hash a password using Bcrypt. My function I use to hash a password is here:

async function genPassword(password) {
  let hashpass = bcrypt.hash(String(password), 9)
  return hashpass
} 

I call this code later during an SQL call here:

const sql = "INSERT INTO USER (userFName, UserLName, userPhone, IsDelete, userEmail, userPassword) VALUES (?, ?, ?, ?, ?, ?);" 
      db.query(sql, [fname, lname, phone, 0, email, String(genPassword(password))], (err, data, fields, ) => { 
//Code to follow omitted

I got this to upload to my database, but got this value in mySQL workbench for the password: Screenshot

As you can see, I get an [Object Promise] instead of the hash. Similarly, I get Promise { <pending> } when I console.log this.

Can anyone see what I may have done incorrectly here? When I hash this in a separate file using bcrypt this works fine, so I am quite confused as to where I have made a mistake.

1 Answers

Maybe you can use this:

const generatePassword = async (password) => {
 return await new Promise((res, rej) => {
  // Your hash logic 
  bcrypt.hash(password, 10, (err, hash) => {
    if (err) rej(err);
    res(hash);
   });
 });
};

When calling it:

 const password = await generatePassword('1234');

The hash method returns a promise so If you don't want to change your code just use async/await or then to resolve the promise value.

Related