I am learning node by doing learnyounode exercises from nodeschool. In the 8th exercise they ask to write a program which does the following:
- takes three URLs as arguments,
- collects data from responses,
- prints them to the console in the same order as in the arguments.
They briefly mention the existence of async libraries which help with counting callbacks but they also invite to complete the exercise without them. My initial solution then was the following:
var http = require('http');
var bl = require('bl');
var results = Array();
var count = 0;
function printResults() {
for (var i = 0; i < 3; i++) {
console.log(results[i]);
}
}
for (var index = 0; index < 3; index++)
http.get(process.argv[2+index], function(response) {
response.pipe(bl(function(err,data){
if(err) console.error(err)
results[index] = data.toString();
count++;
if(count==3) printResults(results);
}));
});
}
This however prints three times "undefined", for some reason. I happened to find the correct solution by simply replacing the for-loop with a function and enclosing the call of that function within another for-loop.
(...)
function httpGet (index) {
http.get(process.argv[2+index], function(response) {
response.pipe(bl(function(err,data){
if(err) console.error(err)
results[index] = data.toString();
count++;
if(count==3) printResults(results);
}));
});
}
for (var i = 0; i < 3; i++)
httpGet(i)
However, I don't understand how exactly this difference made the solution work. Can anyone please enlighten me?
via Marcin Wasilewski
No comments:
Post a Comment