Reputation: 1657
How do I make a multiple requests to one endpoint in one request? I found an async library that allows you to do that but I seem to be implementing it incorrectly.
I have an [] of batches[1,2,3... 18] that I make thru a previous request then I want to pass the elements of batches[] to an endpoint which will give me all the people in a batch as a promise. Here is the code:
var allPeople = [];
var allBatches = [];
app.get('/allpeople', function(req, res){
async.each(allBatches, function(id){
//console.log(id);
client.batches.people(id)
.then(function(people){
allPeople.push(people);
console.log(people)
res.send(people)
})
})
})
app.get('/batches', function(req, res){
client.batches.list()
.then(function(batches) {
batches.forEach(function(batch){
allBatches.push(batch)
});
res.send(allBatches)
})
})
allPeople[] should ultimately be an array of 18 arrays of people objects.
Any idea where im going wrong?
Upvotes: 2
Views: 56
Reputation: 1078
You are missing callback(err) function.
Arguments
Upvotes: 3
Reputation: 381
Your need to call callback() function to iterate over all value of your bathes array. Now it is Iterating only on first value and returning resonse. Try to implement like above code:
async.each(batches, function(id, callback) {
client.batches.people(id)
.then(function(people){
allPeople.push(people);
callback();
})
}, function(err) {
//Handle Final response here
if( err ) { return console.log(err); }
res.json({'peoples':allPeople});
});
Upvotes: 0