Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Resolving bcrypt return promise

Im trying to pass the result of the bcrypt hashing function into the user model below.

I can’t seem be able to wrap my head around how to efficiently resolve this promise.

Heres the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

router.post("/", async (req, res) => {
  req.body = sanitize(req.body);

  // SHA-256
  /* const bitArray = sjcl.hash.sha256.hash(req.body.data[2].value);
  const passwordHashed = sjcl.codec.hex.fromBits(bitArray); */

  const saltRounds = 10;

  const password = req.body.data[2].value;
  var passwordHashed;

  async function hash() {
    return await bcrypt.hash(password, saltRounds, function (err, hash) {});
  }

  const user = new User({
    username: req.body.data[0].value,
    email: req.body.data[1].value,
    password: hash(),
  });

  try {
    await user.save();
    res.status(200).json({ msg: "Success" });
  } catch (e) {}
});

That is what I have tried so far, which is probably wrong

>Solution :

Don’t pass a callback to bcrypt.hash and then you can await it.

const user = new User({
    username: req.body.data[0].value,
    email: req.body.data[1].value,
    password: await bcrypt.hash(password, saltRounds),
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading