1

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!

0

2 Answers 2

1

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);
                }

            })
        });
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Then you have to use promise , providing you snippet . @VirajPatil
vs code says "await has no effect on this expression"
Updated the code . @VirajPatil . It is working fine
Thank you so much @Pushprajsinh Chudasama ! Worked!!! Just edit console.log(classid) to console.log(res) in your answer :D thank you man
0

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);
});

1 Comment

i tried to return the promise but still got undefined ;_; <br> teacherController.getClassid = (req)=>{ Teacher.findOne({token:req.session.user}).lean() .then( (doc)=>{ let promise = new Promise((reslove,reject)=>{ var classid = doc.class reslove(classid); }) return promise; }).catch((err)=>{ if(err) throw err; }) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.