【发布时间】:2014-03-03 15:18:49
【问题描述】:
我尝试根据猫鼬查询的结果过滤数组。标准过滤器函数期望回调返回 true 或 false。我的麻烦是这些信息取决于猫鼬 findOne 查询的异步结果
# code that does not work
myArray.filter = (elem) ->
MyCollection.findOne {_id : elem}, (err,elem) ->
result = err==null
#Need to wait here for the result to be set
result
有人知道如何解决这种问题吗?
我也尝试过使用异步过滤器功能,但我认为它不适用于我的情况(或者我可能不太了解)
这是我对异步过滤器的理解以及为什么(我认为)它不能解决我的问题:
// code that doesn't work
async.filter(myArray, function(elem){
var result = true;
MyCollection.findOne({_id : elem}, function(err,elem) {
result = err==null;
});
// the filter exits without waiting the update done asychronously in the findOne callback
return result;
},
function(results){
// results now equals an array of the existing files
});
【问题讨论】: