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
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.