I've been trying to study on my own the basics of promises, async calls and how to chain them in AngularJS. Currently I'm maintaining an app that likes to use them everywhere, and as a novice they're really overwhelming to say the least.
First off, I have this code in the server-side (node.js) that retrieves a list of a manager's direct reports. This was how the previous dev did it, so I used it as a guide:
exports.findDirectReports = function (req, res) {
var empnum = req.params.empnum;
queries.getDirectReports(empnum)
.then(function (users) {
return res.json(users);
})
.catch(function (err) {
handleError(res, err);
});
};
What I understood (or thought I understood):
queries.getDirectReports
will execute first and return list as a promise.- Resolved promise will be returned inside the
then()
. return res.json(users)
result will then be passed back to whoever called it to be used in other operations.
My problem is getting the resolved promise. I'm aware that I won't get the results right away since it's async
. But I have a find()
that uses these results as a condition, and everytime I check the results I always get null
or []
.
- Is there a way to get them immediately?
- If there are none, how can I execute my other function as soon as the results are ready?
Here's the function in question (also server-side node.js):
exports.downloadEmployee = function (req, res) {
/*
"queries" - alias for another server-side node.js (not really sure what to call
this exactly) that contains the entire getDirectReports fxn.
*/
queries.getDirectReports(empnum)
.then(function (users) {
EmployeeInfo.find({}, function (err, results) {
var tempCtr = [];
if (err) { return err; }
/*
Use results of getDirectReports here as condition
where if employee exists, program will execute
_.forEach below.
*/
_.forEach(results, function (item) {
tempCtr.push({
employeeID: item.employeeID,
employeeName: item.employeeName
});
});
return res.json(tempCtr);
});
})
.catch(function (err) {
handleError(res, err);
});
}
I've seen somewhere here in SO that I need to take advantage of callbacks
, but I don't really understand how. Some of the code samples were similar to the ones I've previously tried (but didn't work).
Any answers will be greatly appreciated.
Thank you.