【问题标题】:SailsJS + Waterline concurrent db requests with promisesSailsJS + Waterline 带有承诺的并发数据库请求
【发布时间】:2014-05-30 10:01:59
【问题描述】:

我对 SailsJS 的水线中的并发性有点困惑。 目前我正在做这样的数据检索;

var results = {};

// Get user by id 5
User.find('5', function(err, user) {
  results.user = user;

  // when it resolves, get messages
  Message.find({userId: '5'}, function(err, messages) {
    results.messages = messages;

    // when message query resolves, get other stuff
    OtherStuff.find({userId: '5'}, function(err, otherStuff) {
      results.otherStuff = otherStuff;

      res.view({results});      
    });
  });
});

问题是数据库调用不是并发的。每个请求都在前一个的承诺得到履行后启动。我想同时启动所有请求,然后以某种方式查看是否所有承诺都已实现,如果是,则继续将结果传递给视图。

如何通过数据库请求实现这种并发?

谢谢!

【问题讨论】:

  • 你甚至没有使用承诺?

标签: node.js asynchronous concurrency sails.js waterline


【解决方案1】:

使用async.autoasync 模块在 Sails 中是全球化的:

async.auto({

    user: function(cb) {
        // Note--use findOne here, not find!  "find" doesn't accept
        // an ID argument, only an object.
        User.findOne('5').exec(cb);
    },
    messages: function(cb) {
        Message.find({userId: '5'}).exec(cb);
    },
    otherStuff: function(cb) {
        OtherStuff.find({userId: '5'}).exec(cb);
    }

},

    // This will be called when all queries are complete, or immediately
    // if any of them returns an error
    function allDone (err, results) {

        // If any of the queries returns an error,
        // it'll populate the "err" var
        if (err) {return res.serverError(err);}

        // Otherwise "results" will be an object whose keys are
        // "user", "messages" and "otherStuff", and whose values
        // are the results of those queries
        res.view(results);

    }
);

【讨论】:

  • 这真的很酷 - 就像一个魅力!感谢您的回答
猜你喜欢
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 2015-02-21
  • 2018-08-11
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多