Your current approach won't work since getStories are async (assumption based on the method signature of getStories
). If you can, I would suggest that you create a method on pivotal
that can get stories for multiple project ids, so your code would read:
app.get('/stories', function(req, res) {
var project_ids = [1, 2];
pivotal.getStories(project_ids, function(err, project_stories) {
res.send(project_stories);
}
});
If that is not an option, I would suggest that you look into a flow library like e.g. node-seq. Then you code could read something like this:
app.get('/stories', function(req, res) {
var project_ids = [1, 2];
Seq(project_ids)
.parEach(function(project_id) {
pivotal.getStories(project_id, this);
})
.seq(function() {
var aggregatedStories = [];
Hash.map(this.args, (function(arg) {
// Each parSeq aparently results in an array of objects
aggregatedStories.push(arg[0]);
}));
res.send(aggregatedStories);
});
});
The Hash.map
function is from a node module called hashish
Edit: To elaborate a little more, parEach
will execute the functions in parallel, and the following seq
would execute after all the callbacks from the parallel executions have finished. node-seq
puts the result from each parallel execution into the parameter array of the following seq
, hence the somewhat cryptic Hash.map(this.args)