使用 mongoose 完成两个异步查询后进行回调

发布于 2024-10-03 09:02:44 字数 312 浏览 3 评论 0原文

使用猫鼬,我希望在两个不同的查询完成后进行回调。

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦行僧 2024-10-10 09:02:44

我认为你已经找到了解决方案,但无论如何。您可以轻松使用 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
    }
);

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
    }
);
玉环 2024-10-10 09:02:44

我想你想看看类似

https://github.com/creationix/step

I think you want to look at something like

https://github.com/creationix/step

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文