rahul2001
rahul2001

Reputation: 1657

Issue making async GET request in Expressjs

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

Answers (2)

sachin.ph
sachin.ph

Reputation: 1078

You are missing callback(err) function.

Arguments

  • arr - An array to iterate over.
  • iterator(item, callback) - A function to apply to each item in arr. The iterator is passed a callback(err) which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicit null argument.
  • callback(err) - A callback which is called when all iterator functions have finished, or an error occurs.

Upvotes: 3

Karan Patyal
Karan Patyal

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

Related Questions