使用猫鼬,我希望在两个不同的查询完成后进行回调。
var team = Team.find({name: 'myteam'});
var games = Game.find({visitor: 'myteam'});
那么假设我希望这些请求非阻塞并异步执行,如何在 Promise 中链接和/或包装这两个请求?
我想避免以下阻塞代码:
team.first(function (t) {
games.all(function (g) {
// Do something with t and g
});
});
我认为你已经找到了解决方案,但无论如何。您可以轻松使用async https://github.com/caolan/async图书馆。在这种情况下,您的代码将如下所示:
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
}
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)