0

Explain how to implement it synchronously and how it works?

let user = req.body;

if (user.user_password) {
    bcrypt.hash(user.user_password, config.salt.saltRounds, (err, hash) => {
        user.user_password = hash;
        console.log(user)
    });   
}
console.log(user)
fiza khan
  • 1,280
  • 13
  • 24
MegaRoks
  • 898
  • 2
  • 13
  • 30
  • Why is it asynchronous? – Chance Feb 26 '19 at 06:32
  • 1
    Your code is asynchronous. In your code you have a callback function which is ran once your `hash` is complete. While your `hash` is "computing", instead of halting the rest of your program, your other code runs, thus executing the bottom `console.log`. Then when you're `hash` is complete, it will call the callback function, thus executing your second `console.log` – Nick Parsons Feb 26 '19 at 06:34
  • are you using promises or async await for your functions? – Sohan Feb 26 '19 at 07:11

1 Answers1

2

Bcrypt is intentionally slow to prevent faster hardware to easily crack your hashes, for this reason it executes asynchronously to avoid locking your app at that point.

Check this link: Hashing in Action: Understanding bcrypt

Nevetheless the following solution will "look" synchronously.

async function foo() {
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
}

foo();
console.log(this.password);