Skip to content
Advertisement

Gettting an undefined value from bcrypt hash function

Ok, I’m getting an undefined value from a function, I don’t know why, I’m trying to get the value of a password hash for insert in the database, but the const that have the function has the value “undefined”, so what I should change in my code?

async postCompletedetails(req, res) {
  const company = req.params.company;
  const name = req.params.name;
  const password = req.params.password;
  const hashPass = await bcrypt.hash(password, saltRounds, function(err, hash) {
    if (err) {
      throw err
    } else {
      console.log(hash)
    }
  })



  if (
    company !== undefined &&
    name !== undefined &&
    password !== undefined
  ) {

    const {
      token
    } = req.headers;
    const decoded = jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION);
    const id = decoded.id;

    const update = await pool.query(
      `UPDATE user SET Name_user= '${name}', password= '${hashPass}' WHERE ID_user = ${id}`
    );
    const incompany = await pool.query(
      `INSERT INTO company (Name_company) VALUES ('${company}') `
    );

    const inrelcompany = await pool.query(
      `INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), ${id})`
    );

    return res.json({
      code: 200,
      message: "todo bien... todo correcto y yo que me alegro",
      hashPass,
      password
    });
  } else {
    return res.json({
      code: 400,
      message: "Bro hiciste algo mal",
    });
  }
}

Advertisement

Answer

When you call bcrypt.hash() and pass in a callback function, no Promise is returned. You can leave off that callback and then your await will work as you expect.

Basically, as is common with a lot of APIs, you can choose between the “old school” callback function approach or the more modern Promise/async model. One or the other, but not both at the same time.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement