执行几个猫鼬疑问:如何使用的承诺呢?

问题描述:

我有以下的code和我想避免嵌套的回调:

I have the following code and I would like to avoid nested callbacks:

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

任何想法?

我觉得 异步 库比对承诺这样的事情一个清晰的解决方案。对于这个特定的情况下, async.parallel 将工作做好。

I find the async library to be a cleaner solution than promises for this sort of thing. For this specific case, async.parallel would work well.

我不是太熟悉的CoffeeScript,但它会是这个样子:

I'm not overly familiar with coffeescript, but it would look something like this:

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