1

I have the following loops which make 10 requests. The console.log would print from 1 to 10. How do I modify this code to only print out the final length of peopleProfile (10)?

for (var i = 0; i < 10; i++) {
  request(URL, function(err, response, body) {
    if (err) {
      console.log(err);
    }
    if (!err && response.statusCode == 200) {
      peopleProfile.push(body);
      console.log(peopleProfile.length);
    }
  });
}
Bun
  • 3,037
  • 3
  • 19
  • 29
  • 1
    You can't do async and loop, you are basically doing 10 requests concurrently, not sequentially. – elclanrs Feb 17 '16 at 01:53
  • Can you point out a better way to solve this? I'd like to make 10 requests and store each request's response to `peopleProfile`. – Bun Feb 17 '16 at 01:55
  • 1
    I'd aim for something like `sequence(range(1,10).map(request(url))` where `request(url)` returns a promise, and `sequence` takes an array of promises and runs them in order. – elclanrs Feb 17 '16 at 01:56
  • Any objection to use `promises`? – KevBot Feb 17 '16 at 01:57
  • You could count the resolved requests, and the rejected requests and check when the combined total hits 10 – iH8 Feb 17 '16 at 01:57
  • Here's one solution: [How can I throttle stack of api requests?](http://stackoverflow.com/questions/35422377/how-can-i-throttle-stack-of-api-requests/35422593#35422593). – jfriend00 Feb 17 '16 at 02:01
  • you could use `promises` and chain ten calls with `.then` –  Feb 17 '16 at 02:08
  • http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – mattwilsn Feb 17 '16 at 02:15

2 Answers2

2

you can use Bluebird - a promise library for this

var promises = [];
for (var i = 0; i < 10; ++i) {
    promises.push(requestAsync(url));
}
Promise.all(promises).then(function() {
    console.log("print this after finishing 10 requests");
});
Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
  • 1
    this is exactly what I was talking about in my comment! I just do not have the energy to post a solution! –  Feb 17 '16 at 02:16
1

Is there a reason you can't do this?

var completedRequests = 0;

for (var i = 0; i < 10; i++) {
  request(URL, function(err, response, body) {
    completedRequests++;
    if (err) {
      console.log(err);
    }
    if (!err && response.statusCode == 200) {
      peopleProfile.push(body);
      if (completedRequests === 10) {
        console.log(peopleProfile.length);
      }
    }
  });
}
carlevans719
  • 106
  • 5