如何等待猫鼬查询的结果? [英] How to wait for the result of a mongoose query?
问题描述
我尝试根据猫鼬查询的结果过滤数组.标准过滤器函数期望回调返回true或false.我的麻烦是该信息取决于猫鼬findOne查询的异步结果
I try to filter an array according to the result of a mongoose query. The standard filter function expect the callback to return true or false. My trouble is that this information depends on the asynchronous result of a mongoose findOne query
# 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
有人知道如何解决此类问题吗?
Anyone has a clue how to resolve that kind problem ?
我也尝试使用异步过滤器功能,但我认为它不适用于我的情况(或者我可能不太了解)
I tried as well to use the async filter function but I don't think it works in my case (or I maybe I don't understand well)
这是我对异步过滤器的理解,以及为什么(我认为)它不能解决我的问题:
Here is my understanding of async filter and why (I think) it can't solve my problem :
// 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
});
推荐答案
使用 filter
可以从async
库中获取.
更新
您的尝试非常接近,您只需要将结果提供给回调即可,而不是返回它:
You're pretty close in your attempt, you just need to provide the result to the callback instead of returning it:
async.filter(myArray, function(elem, callback){
MyCollection.findOne({_id : elem}, function(err, doc) {
callback(err == null && doc != null);
});
},
function(results){
// results is myArray filtered to just the elements where findOne found a doc
// with a matching _id.
});
这篇关于如何等待猫鼬查询的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!