11 mongoose mongodb node.js promise q
使用mongoose来查询db和Q for promises的结果,但是发现很难找到一个可用的用户列表.目前我有这样的事情:
var checkForPerson = function( person ) {
people = mongoose.model('Person', Person)
return people.findOne({"_id": person }, function(err, doc) {
if (err) console.log(err)
if (doc !== null) {
return doc
} else {
console.log('no results')
}
})
}
var promises = someArrayOfIds.map(checkForPerson);
// this is where I would like to have an array of models
var users = Q.all(promises)
//this fires off before the people.findOne query above to users is undefined
SomeOtherFunction( users )
Run Code Online (Sandbox Code Playgroud)
如果SomeOtherFunction
没有做大量的草率回调,我将如何完成查询?
Wir*_*rie 19
另一个建议是使用MongoDB的$in
运算符传入一个数组find
并有效地获得大量结果.每个都是一个Mongoose对象.
var promise = people.find({ _id: { $in: someArrayOfIds }).exec();
promise.then(function(arrayOfPeople) {
// array of people ... do what you want here...
});
Run Code Online (Sandbox Code Playgroud)
这比制作多个请求(每个请求一个)要高效得多_id
.
"如何继续承诺"这个问题的答案几乎总是如此.then
.这是承诺的类比,;
它终止了一个异步语句.您可以在其中返回承诺,并在继续之前将其解包.
Q.all(promises).then(function(users){
SomeOtherFunction(users);
});
Run Code Online (Sandbox Code Playgroud)
或者干脆 Q.all(promise).then(SomeOtherFunction)
你还需要findOne来实际返回promises.您可以使用Q.nfcall
哪个调用节点函数或自己实现它.
什么Q.all
是接受一系列的承诺和满足当所有这些做和拒绝时,其中一个拒绝.您可能希望.catch
在任何查询失败或使用时附加处理程序.done
以表示链的结尾.其他承诺库如Bluebird即使没有.done
或添加显式处理程序也会为您拾取错误,遗憾的是Q不会这样做.
归档时间: |
|
查看次数: |
16877 次 |
最近记录: |