1

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

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

有任何想法吗?

4

2 回答 2

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
于 2012-11-04T14:18:48.230 回答
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);
};
于 2012-11-04T23:25:01.077 回答