2012-11-04 62 views
1

我有下面的代碼,我想避免嵌套的回調:執行幾個貓鼬查詢:如何使用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 

任何想法?

回答

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 
+0

JohnnyHK,你的代碼已經非常完美, 謝謝! – sigmus

+1

你也可以粘貼在JS? – chovy

+0

粘貼在這裏:https://gist.github.com/4014642 @chovy – sigmus

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

我不確定我們是否在談論這裏的相同情況。 – sigmus

+2

每找到一個回調函數,這是一種平坦化出現的嵌套的方法。我認爲異步庫可能更易於閱讀。 – chovy