2

Sorry if this question is simple but I have been using node.js for only a few days.

Basically i receive a json with some entries. I loop on these entries and launch a http request for each of them. Something like this:

for (var i in entries) {
    // Lots of stuff

    http.get(options, function(res) {
        // Parse reponse and detect if it was successfully
    });
}

How can i detect when all requests were done? I need this in order to call response.end().

Also i will need to inform if each entry had success or not. Should i use a global variable to save the result of each entry?

Fernando
  • 4,459
  • 4
  • 26
  • 39
  • Duplicate of http://stackoverflow.com/questions/5172244/idiomatic-way-to-wait-for-multiple-callbacks-in-node-js/5175674 and http://stackoverflow.com/questions/7721808/how-to-get-the-two-parameters-of-two-asynchronous-functions/7722015 – Ricardo Tomasi Nov 20 '11 at 01:38

2 Answers2

5

You can e.g. use caolans "async" library:

async.map(entries, function(entry, cb) {
  http.get(options, function(res) {
    // call cb here, first argument is the error or null, second one is the result
  })
}, function(err, res) {
  // this gets called when all requests are complete
  // res is an array with the results
}
thejh
  • 44,854
  • 16
  • 96
  • 107
  • If you just simply loop on some items I suggest using `async.each` instead of `async.map`. Since [map](https://github.com/caolan/async#maparr-iterator-callback) will **produces a new array of values by mapping each value**, it would cause more overhead. – Peter Liang Dec 21 '15 at 05:21
0

There are many different libraries for that. I prefer q and qq futures libraries to async as async leads to forests of callbacks in complex scenarios. Yet another library is Step.

nponeccop
  • 13,527
  • 1
  • 44
  • 106