Reputation: 385
I was trying to get jwtauthtoken from user and passing it to a getuserId() which was imported in that js file. But i was getting undefined value instead of decoded id that was returned by the function.
In the getUserId() it displays the decoded token
My console output:
user id 5f68efb234a7656
On get request : undefined
Anyone can help to me resolve the problem.
personalDetailsController.js
module.exports.personaldetail_get = async (req,res) => {
const token = req.cookies.jwtauthtoken;
let userId = await getUserId(token);
console.log("On get request : "+ userId); // output On get request : undefined
res.render('Candidate/personal', { csrfToken: req.csrfToken() });
}
getUserId.js
module.exports.getUserId = (tokenid) => {
const token = tokenid;
try{
if (token) {
jwt.verify(token,'2308199919990823', async (err, decodedToken) => {
if(err){
console.log(err);
return null;
} else {
console.log("user id " + decodedToken.id); // Output user id 5f68efb234a7656
return decodedToken.id;
}
});
} else {
return null;
}
}
catch(err)
{
console.log(err)
return null;
}
}
Upvotes: 0
Views: 949
Reputation: 26360
const decodedToken = await getUserId(token)
means two things :
decodedToken
is given by the resolution of this Promise.getUserId = tokenid => {
return new Promise(resolve => {
jwt.verify(tokenid, '2308199919990823', (err, decodedToken) => resolve(decodedToken))
})
}
Upvotes: 3
Reputation: 1550
you forgot the add a return
on your function call...
Also the try catch block you have will not work since your verify function is asynchronous...you need to wrap this in a Promise...
module.exports.getUserId = (tokenid) => {
const token = tokenid;
if (token) {
return new Promise((reject, resolve) => {
jwt.verify(token,'2308199919990823', async (err, decodedToken) => {
if(err){
console.log(err);
return null;
} else {
console.log("user id " + decodedToken.id); // Output user id 5f68efb234a7656
return resolve(decodedToken.id);
}
});
});
}
}
Upvotes: 1