2

The function works, for scalability and production concerns I would like to turn this exact function into an async function.

userSchema.methods  =   {
  checkPassword: function (inputPassword)   {
  return bcrypt.compareSync( inputPassword, this.password )
},
  hashPassword: plainTextPassword   =>   {
  return bcrypt.hashSync( plainTextPassword, 10 )
}
}

userSchema.pre('save', function (next) {
  if (!this.password) {
  console.log('models/user.js =======NO PASSWORD PROVIDED=======')
  next()
} else {
  console.log('models/user.js hashPassword in pre save');
  this.password = this.hashPassword(this.password)
  next()
  }
})

3 Answers3

3

Although it is already available, if you really wanted to await a callback style control flow...

const hashAsync = (plainTextPassword) => {
  return new Promise((resolve, reject) => {
    bcrypt.hash(plainTextPassword, 10, (err, hash) => {
      if (err) reject(err)
      resolve(hash)
    })
  }
}

We simply wrap the callback based brcypt.hash in a new Promise and can now await hashAsync

camwhite
  • 837
  • 8
  • 13
1

https://www.npmjs.com/package/bcryptjs

You are using the synchronous versions of the bcrypt functions. There are async versions available already

bcrypt.compareSync can be bcrypt.compare() which returns a promise if no callback is provided, or will call your callback function if it is provided.

Same for bcrypt.hashSync( plainTextPassword, 10 )can be changed to bcrypt.hash.

The documentation on npm includes a full list of the sync and async versions of each function.

Cal Irvine
  • 1,104
  • 8
  • 17
0

This answer on Stack Overflow may be helpful for you. It describes exactly how to embed a bcrypt function into an async-function.

MarvMan
  • 41
  • 9