Reputation: 35
I am trying to return a value from module function and calling that function from different file, the function executes but return undefined
below is the code:
this is the module
teacherController={}
teacherController.getClassid = (req)=>{
Teacher.findOne({token:req.session.user})
.then((doc)=>{
var classid = doc.class
console.log(classid) // this logs the correct value
return doc;
}).catch((err)=>{
if(err) throw err;
})
}
module.exports = teacherController;
this is where i am calling the module function
student.get('/ranking',(req,res)=>{
var classid = teacher_con.getClassid(req);
console.log(classid); //this logs: undefined
});
thank you!
Upvotes: 1
Views: 186
Reputation: 7949
EDITED
You have to use the promise and thenable function
.
student.get('/ranking',(req,res)=>{
teacher_con.getClassid(req).then(res =>{
console.log(classid); //you will get the doc
});
});
In module
teacherController.getClassid = (req)=> { //use Promise
return new Promise((resolve, reject)=>{
Teacher.findOne({token:req.session.user})
.exec((err, doc)=>{
if(err){
reject(err);
}
else{
resolve(doc);
}
})
});
}
Upvotes: 1
Reputation: 16147
Return a promise in getClassid
function:
teacherController = {}
teacherController.getClassid = (req) => {
return Teacher.findOne({ token: req.session.user })
.then((doc) => {
var classid = doc.class
console.log(classid) // this logs the correct value
return doc;
}).catch((err) => {
if (err) throw err;
})
}
module.exports = teacherController;
Then, use async/await
at your route:
student.get('/ranking', async (req, res) => {
var classid = await teacher_con.getClassid(req);
console.log(classid);
});
Upvotes: 0