使用mongoose,我希望在完成2个不同的查询后进行回调.
var team = Team.find({name: 'myteam'});
var games = Game.find({visitor: 'myteam'});
然后如何假设我希望这些请求不阻塞并异步执行,如何在promises中链接和/或包装这两个请求?
我想避免以下阻止代码:
team.first(function (t) {
games.all(function (g) {
// Do something with t and g
});
});
Cra*_*row 12
我想你已经找到了解决办法但无论如何.您可以轻松使用异步库.在这种情况下,您的代码将如下所示:
async.parallel(
{
team: function(callback){
Team.find({name: 'myteam'}, function (err, docs) {
callback(err, docs);
});
},
games: function(callback){
Games.find({visitor: 'myteam'}, function (err, docs) {
callback(err, docs);
});
},
},
function(e, r){
// can use r.team and r.games as you wish
}
);
Run Code Online (Sandbox Code Playgroud)