Nick
Nick

Reputation: 77

How to return hashed password with bcrypt?

Im using bcrypt and I'm trying to use an async function that hashes a password and returns it but since its async unless I use the sync version (which I don't want even though it works) it returns [object Promise] and the database saves this: {} as the password. Yes two brackets. I do use await but it does not work and my poor understanding of async functions is getting in the way. I can't find any answers online since it looks like I'm doing it all right according to the tutorials but I obviously am not.

The code looks like this:

function signup(){
     var pass = "example";
     pass = hashPassword(pass);
     
     console.log(pass); // prints [object Promise] - It's printed first.

     //write account with pass to database. Pass is saved as '{}'.
}

async function hashPassword(original_password){
     const hashedPass = await bcrypt.hash(original_password, 10);
     console.log(hashedPass) // prints the actual hashed pass - It's printed second

     return hashedPass; //returns [object Promise]
}

So how can I have it return the hashed password without adding the send-to-database code inside the async?

Upvotes: 1

Views: 1878

Answers (2)

Shivam
Shivam

Reputation: 3642

When you call an async function it will return a promise, check out this answer on SO.

In order to get your hashed data you can use .then to resolve your promise

hashPassword(pass).then(hash=>console.log(hash)).catch(err=>console.error(err))

Or you can use async/await as well

async function signup() {
  try {
    var pass = "example";
    pass = await hashPassword(pass);
  } catch (err) {
    console.error(err);
  }
}

Upvotes: 2

WhoAmI
WhoAmI

Reputation: 145

bcrypt.hash does not return a promise.

You may need to wrap this function call into a new promise

const hashedPass = await new Promise((resolve, reject) => {
    bcrypt.hash(original_password, rounds, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });

Upvotes: 3

Related Questions