1

I am trying to generate hashed password using bcrypt and log it in terminal. But the logged result is not as per my expected output

My controller function is as follows,

const User = require('../models/user');
const { hashedPassword } = require('../lib/passwordHash');

exports.create = (req, res) => {
  const { body } = req;

  console.log('1 Create');

  const { password } = body;
  console.log('2 ', password);

  const newPassword = hashedPassword(password);
  console.log('3 ', newPassword);

  res.send('Create');
};

passwordHash.js is as follows,

const bcrypt = require('bcrypt');

const saltRounds = 10;

const hashedPassword = (password) =>
  bcrypt.hash(password, saltRounds, (err, hash) => {
    if (err) {
      return err;
    }
    console.log(hash);
    return hash;
  });

module.exports = {
  hashedPassword
};

Output is as follows,

1 Create
2  12345
3  undefined
$2b$10$hVQ7J4ratfP7ubgiRzF1WOI7rmYC5WRo4kFh6EbjJtK0qR1gW5nWa

Expected the Output to be,

1 Create
2  12345
$2b$10$hVQ7J4ratfP7ubgiRzF1WOI7rmYC5WRo4kFh6EbjJtK0qR1gW5nWa
3 $2b$10$hVQ7J4ratfP7ubgiRzF1WOI7rmYC5WRo4kFh6EbjJtK0qR1gW5nWa

I understand that it is an asynchronous function which runs after all the lines are executed. But how can i get the expected result.

Rafael
  • 499
  • 1
  • 3
  • 12

0 Answers0