I was looking for an answer and found this. Like in jquery there is when
function. Using some guidelines to synchronize my asynchronous calls I am using async.js
in Node
Here is the code.
async.forEach(dateInDateFormat, function(item, callback) {
console.log(moment(item.startDate).toDate());
var result = Trip.aggregate([{
"$unwind": "$trips"
}, {
"$match": {
"trips.startTime": {
"$gte": moment(item.startDate).toDate(),
"$lte": moment(item.endDate).toDate()
}
}
}, {
"$group": {
"_id": {
"date": {
"$dayOfMonth": "$trips.startTime"
}
},
"distance": {
"$sum": "$trips.distance"
}
}
}]);
result.exec(function(err, doc) {
console.log(doc);
});
console.log("Executing callback");
callback();
}, function(error) {
console.log("Loop over");
});
This is the output.
Executing callback
Loop over
[ { _id: { date: 23 }, distance: 0 },
{ _id: { date: 22 }, distance: 0 },
{ _id: { date: 21 }, distance: 0 } ]
[ { _id: { date: 29 }, distance: 210 },
{ _id: { date: 27 }, distance: 210 },
{ _id: { date: 26 }, distance: 210 },
{ _id: { date: 25 }, distance: 0 } ]
[]
As you can see. Executing callback and Loop over are executed before I get the data. I cannot send it back to my Angular Frontend using res.send()
.
One answer is you cannot return a value from a asynchronous function. You only return a callback. How do I do that in this case?
Or
How do I use the async.series([])
function. Because I used that also and even that is not giving me exact results.
Thanks
EDIT Answer in short, the position of callback function matters. If you give it at wrong place don't expect write answers. Please see the code in the answer and comment thread for better explanation.