Trying to hash a password using bcrypt inside an async function

use The method bcrypt.hashSync(), It is Synchronous out of the box.

const hashedPassword = bcrypt.hashSync(password,saltRounds);

await dosent wait for bcrypt.hash because bcrypt.hash does not return a promise. Use the following method, which wraps bcrypt in a promise in order to use await.

async function hashPassword (user) {

  const password = user.password
  const saltRounds = 10;

  const hashedPassword = await new Promise((resolve, reject) => {
    bcrypt.hash(password, saltRounds, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });
  })

  return hashedPassword
}

Update:-

The library has added code to return a promise which will make the use of async/await possible, which was not available earlier. the new way of usage would be as follows.

const hashedPassword = await bcrypt.hash(password, saltRounds)

By default, bcrypt.hash(password,10) will return as promise. please check here

Example: Run the code,

var bcrypt= require('bcrypt');

let password = "12345";


var hashPassword = async function(){
    console.log(bcrypt.hash(password,10));
    var hashPwd = await bcrypt.hash(password,10);
    console.log(hashPwd);
}

hashPassword();

Output:

Promise { <pending> }
$2b$10$8Y5Oj329TeEh8weYpJA6EOE39AA/BXVFOEUn1YOFC.sf1chUi4H8i

When you use await inside the async function, it will wait untill it get resolved from the promise.