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?
Assuming the getFiltersByFilterCategory function is defined on the window object (defined on the global scope). The undefined is logging because the function is ultimately being called with a context that is not window, so to fix this you can declare the function as a variable within the closure where it's still within scope.
I.e. Below, (obviously a cleaner solution would be restructured.)
function getAllFilters(allFilters){
var allFiltersWithCount =[];
var getFiltersByFilterCategory = function(name){ };
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));
});
}
});