I have an ajax call that is inside a forEach loop which is inside another function.
The problem is, that the callback of the outer function fires before the inner loop ends – so “staticItemList” is not filled with the items when passed to the callback.
How can I fix that ? I really spent a lot of hours on that. Thanks.
exports.buildTheList = function (parsedList, callback) {
var staticItemList = {};
parsedList.forEach(function(parsedItem) {
db.staticList.find({"_id":parsedItem.ID}).forEach(function(err, doc) {
if (!doc){
console.log("newStaticItem not found in db");
parsedDataFetcher.fetchParsedDetails(Path, function(parsedDetails){
staticItemList["_id"] = parsedItem.ID;
staticItemList[parsedItem.ID] = {
"_id": parsedItem.ID,
"type": parsedItem.type,
}
})
}else {
console.log("newStaticItem already found in db");
}
});
});
callback(staticItemList);
}
Add a counter variable inside the loop, and decrement it every time the async methods complete. Once the counter hits zero, call callback. In pseudo-code:
Hope that helps.