使用mongoose完成两个异步查询后有一个回调 [英] Having a callback after two asynchronous queries have completed using mongoose

查看:141
本文介绍了使用mongoose完成两个异步查询后有一个回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用猫鼬,我想在2个不同的查询完成后进行回调.

Using mongoose, I would like having a callback after 2 different queries have completed.


var team = Team.find({name: 'myteam'});
var games = Game.find({visitor: 'myteam'});

然后假设我希望这些请求无阻塞并异步执行,那么如何在promise中链接和/或包装这两个请求?

Then how to chain and/or wrap those 2 requests within promises assuming I want those requests non blocking and executed asynchronously?

我想避免以下阻止代码:

I would like to avoid the following blocking code:


team.first(function (t) {
  games.all(function (g) {
    // Do something with t and g
  });
});

推荐答案

我认为您已经找到了解决方案,但是无论如何.您可以轻松使用 async 库.在这种情况下,您的代码将如下所示:

I think you already found solution but anyway. You can easily use async library. In this case your code will looks like:

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
    }
);

这篇关于使用mongoose完成两个异步查询后有一个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆