when I call UserService.signUp()
from index.js
then my var x
is undefined. apparently my function singUp()
returns back to my router.post
function after await hash()
. how can I fix this issue? I would like for the signUp
function to wait for the hash
function to complete, before the function returns.
index.js:
router.post('/register', (req, res) => {
var username = req.body.username,
password = req.body.password,
email = req.body.email
var x = UserService.signUp(username, password, email);
console.log("debug")
if (x.success) {
...
}
})
auth.js:
async function signUp(username, password, email) {
....
try {
var salt = generateSalt()
console.log("generated salt")
var passwordHash = await hash(password, salt)
console.log("generated hash")
} catch (err) {
console.error(err)
}
UserModel.createUser()
return {
success: true,
description: 'User was created'
}
}
function hash(password, salt) {
return pbkdf2(password, salt, 10000, 64, 'sha512');
}
user.js:
function createUser(username, email, salt, hash) {
...
console.log("created user")
return true
}
current output (wrong):
generated salt
debug
POST /register 200 17.164 ms - -
generated hash
created user
desired output:
generated salt
generated hash
created user
debug
POST /register 200 17.164 ms - -
CodePudding user response:
You're not awaiting the function:
var x = UserService.signUp(username, password, email);
Either make the containing function async
and await
the result:
router.post('/register', async (req, res) => {
//...
var x = await UserService.signUp(username, password, email);
//...
});
Or append a .then()
to handle the result of the Promise
:
UserService.signUp(username, password, email).then(x => {
console.log("debug")
if (x.success) {
//...
}
});