I want to call a function inside a loop. This function returns undefined, while the log shows me the correct output in the function.
Where i call the function:
function getAllFilters(allFilters){
var allFiltersWithCount =[]
allFilters.forEach(function(item){
if(item.name != null || typeof(item.name) != 'undefined') {
allFiltersWithCount.push(function (callback){
console.log("inloop" + getFiltersByFilterCategory(item.name) );
callback(null,getFiltersByFilterCategory(item.name));
});
}
});
async.parallel(allFiltersWithCount, function(err, result) {
console.log("results " + result);
return allFiltersWithCount;
});
}
And a part of the function i'm calling:
function getFiltersByFilterCategory(filterCategory){
switch(filterCategory){
case "prescription":
ProductSchema.aggregate(
{
$group:
{_id: '$prescription', total: {$sum:1}}
},
function(err,res){
var toreturn = {name:"prescription",filters: sort(res)};
console.log(toreturn);
return toreturn;
})
case "usage": {...}
in my log I see:
inloopundefined (multiplied by the number of loops)
results ,,,,,
{ name: 'prescription',
filters:
[{...},{...},...]
So I'm guessing it runs this function async. But how does javascript let me do this correctly and what is really happening? Does he returns the function to early, and then just do the console.log afterwards? Or what?