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?
JavaScript
x
51
51
1
async postCompletedetails(req, res) {
2
const company = req.params.company;
3
const name = req.params.name;
4
const password = req.params.password;
5
const hashPass = await bcrypt.hash(password, saltRounds, function(err, hash) {
6
if (err) {
7
throw err
8
} else {
9
console.log(hash)
10
}
11
})
12
13
14
15
if (
16
company !== undefined &&
17
name !== undefined &&
18
password !== undefined
19
) {
20
21
const {
22
token
23
} = req.headers;
24
const decoded = jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION);
25
const id = decoded.id;
26
27
const update = await pool.query(
28
`UPDATE user SET Name_user= '${name}', password= '${hashPass}' WHERE ID_user = ${id}`
29
);
30
const incompany = await pool.query(
31
`INSERT INTO company (Name_company) VALUES ('${company}') `
32
);
33
34
const inrelcompany = await pool.query(
35
`INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), ${id})`
36
);
37
38
return res.json({
39
code: 200,
40
message: "todo bien... todo correcto y yo que me alegro",
41
hashPass,
42
password
43
});
44
} else {
45
return res.json({
46
code: 400,
47
message: "Bro hiciste algo mal",
48
});
49
}
50
}
51
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.