I'm trying to follow the NodeSchool tutorials on async principles. There is a lesson with the requirement to:
- make asynchronous GET requests to 3 URLs
- collect the data returned in HTTP responses using callbacks
- print the data collected from each response, preserving the order of the correlating input URLs
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.
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:
var http = require('http');
var replies = 0;
var results = ['','',''];
var running = '';
for(var i = 2; i < 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 < 3; i++) {
console.log(totals[i]);
}
}
}
How can I get the callback to recognize which GET its response is a response to?
Note: the assignment specifically prohibits the use of 3rd party libs such as async or after.
Edit: 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:
response.on('data', function(data) {
results[i-2] += data;
});
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.)