0

This is my Logic in one of my controller method

exports.index = function(req, res) {

   var empRole;
   EmpModel.findById(empId, null ,function(err, emp) {

      if(emp) {
         empRole = emp.role;          
      }
   });

   console.log("Emp Role : " + empRole);      // This will return undefined
};

How can I get the value of empRole from the call back function

Ranjith
  • 2,779
  • 3
  • 22
  • 41
  • "[How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)" will likely be a worthwhile read. Though it uses Ajax via jQuery as the example, the same restraints and options apply to all asynchronous operations, including database queries with Mongoose. – Jonathan Lonowski Aug 13 '14 at 05:33

1 Answers1

0

You can pass a callback to the index function and inside the "IF" condition use the callback to pass the value to the caller.

Example:

exports.index = function(callback) {

   var empRole;
   EmpModel.findById(empId, null ,function(err, emp) {

      if(emp) {
         empRole = emp.role;
         callback(empRole)
      }
   });


};

You need to invoke the index function like this:

index(function(emprole){
      //this function is executed once the findById completes
      console.log("Emp Role : " + empRole); 
});

Look into Callback's in javascript along with Closure to understand this better.

Community
  • 1
  • 1
Errol Dsilva
  • 177
  • 11
  • But i have `req, res` in functional params in `index` method. – Ranjith Aug 13 '14 at 05:37
  • The actual scenario is when index called i get the empId from query param `(req.query.empId)` also with optional filter params. And check if the Employee exists and grap some value from that particular employee atlast filter the all employees with necessary filter option. – Ranjith Aug 13 '14 at 05:42
  • Please look into Callbacks; as javascript is asynchronous return wont work. Also in the actual code if you move the console.log right after the if(emp) condition ends i.e. the } bracket you should have the value printed. – Errol Dsilva Aug 13 '14 at 06:26