执行几个mongoose查询:如何使用promises?

时间:2012-11-04 14:09:35

标签: asynchronous coffeescript express mongoose promise

我有以下代码,我想避免嵌套回调:

app.get '/performers', (req, res) ->
    conductor = require('models/conductor').init().model
    soloist = require('models/soloist').init().model
    orchestra = require('models/orchestra').init().model
    chamber = require('models/chamber').init().model
    performers = {}
    conductor.find {}, (err, result) ->
        performers.conductor = result
        soloist.find {}, (err, result) ->
            performers.soloist = result
            orchestra.find {}, (err, result) ->
                performers.orchestra = result
                chamber.find {}, (err, result) ->
                    performers.chamber = result
                    res.json performers

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

我发现async库比这种事情的承诺更清晰。对于这种特定情况,async.parallel会很好。

我对coffeescript并不过分熟悉,但它看起来像这样:

performers = {}
async.parallel [
    (callback) ->
        conductor.find {}, (err, result) ->
            performers.conductor = result
            callback err
    (callback) ->
        soloist.find {}, (err, result) ->
            performers.soloist = result
            callback err
    (callback) ->
        orchestra.find {}, (err, result) ->
            performers.orchestra = result
            callback err
    (callback) ->
        chamber.find {}, (err, result) ->
            performers.chamber = result
            callback err
    ], (err) ->
        res.json performers

答案 1 :(得分:1)

您还可以像这样组织代码:

exports.index = function(req, res){
    var _self = {};

    var foundItems = function(err, items){
      _self.items = items;
      res.render('index', { user: _self.user, items: _self.items, lists: _self.lists });
    };

    var foundLists = function(err, lists){
      _self.lists = lists;
      Items.find().exec(foundItems);
    };

    var foundUser = function(err, user){
      _self.user = user;
      List.find().exec(foundLists);
    };

    User.findById(user).exec(foundUser);
};