title: Node.JS - How to identify which async HTTP GET response is returning data in a callback?
body: <p>I'm trying to follow the NodeSchool tutorials on async principles.  There is a lesson with the requirement to:</p>
  
  <ul>
  <li>make asynchronous GET requests to 3 URLs</li>
  <li>collect the data returned in HTTP responses using callbacks</li>
  <li>print the data collected from each response, <em>preserving the order of the correlating input URLs</em></li>
  </ul>
  
  <p>One way I thought of doing this was to make 3 separate callbacks, each writing to its own dedicated buffer.  But this seemed like a poor solution to me, because it requires code duplication and is not scalable.  However, I am stuck on figuring out another way to get a callback to remember "where it came from" for lack of a better term.  Or what order it was called in, etc.</p>
  
  <p>I feel like I'm close, but I've been stuck at 'close' for long enough to look for help.  Here's the closest I've felt so far:</p>
  
  <pre><code>var http = require('http');
  
  var replies = 0;
  var results = ['','',''];
  var running = '';
  
  for(var i = 2; i &lt; 5; i++) {
      http.get(process.argv[i], function (response) {
          response.setEncoding('utf8');
          response.on('data', handleGet);
          response.on('error', handleError);
          response.on('end', handleEnd);
      });
  }
  
  function handleGet(data) {
      running += data;
  }
  
  function handleError(error) {
      console.log(error);
  }
  
  function handleEnd() {
      results[replies] = running;
      running = '';
      replies++;
      if(replies === 3) {
          for(var i = 0; i &lt; 3; i++) {
              console.log(totals[i]);
          }
      }
  }
  </code></pre>
  
  <p>How can I get the callback to recognize which GET its response is a response to?</p>
  
  <p><strong>Note:</strong> the assignment specifically prohibits the use of 3rd party libs such as <em>async</em> or <em>after</em>.</p>
  
  <p><strong>Edit:</strong> another thing I tried (that also obviously failed), was inlining the callback definition for handleGet like so, to try and preserve the 'index' of the callback:</p>
  
  <pre><code>response.on('data', function(data) {
      results[i-2] += data;
  });
  </code></pre>
  
  <p>On execution, this always indexes to results[3] because the async callbacks don't happen until after the for loop is already long done.  (Actually I'm not sure why the value of i is preserved at 5 at all, since the completed for loop would go out of scope, as I understand it... I would have thought it'd be undefined in retrospect.)</p>