我想在循环内调用一个函数。 该函数返回未定义,而日志显示了函数中的正确输出。
我在哪里调用该函数:
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;
});
}
以及我正在调用的函数的一部分:
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": {...}
在我的日志中我看到:
inloopundefined (multiplied by the number of loops)
results ,,,,,
{ name: 'prescription',
filters:
[{...},{...},...]
所以我猜测它异步运行这个函数。但是 javascript 如何让我正确地做到这一点以及到底发生了什么?他是否将函数返回到早期,然后只执行console.log?或者什么?
最佳答案
假设 getFiltersByFilterCategory 函数是在 window 对象上定义的(在全局范围内定义)。未定义的是日志记录,因为该函数最终是在不是窗口的上下文中调用的,因此要解决此问题,您可以将该函数声明为闭包中的变量,该变量仍在范围内。
即下面,(显然会重组一个更清洁的解决方案。)
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));
});
}
});
关于javascript - 函数返回未定义,而日志显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150663/