I'm working through the fabously-named learnyounode. #9 is "JUGGLING ASYNC" and the instructions are to take in 3 urls as params and output the content in parameter order. I got it working by including a counter, but my original did not work:
var http = require('http'),
bl = require('bl'),
store = [],
count = 0; //added later
process.argv.forEach(function(element, index, array) {
if (index > 1) {
http.get(element, function(response) {
response.pipe(bl(function(err, data) {
store[index] = data.toString();
count++; //added later
if (store.length == 3) {
store.forEach(function(e,is,a) {
console.log(e);
});
}
}));
});
}
});
Now the thing works fine if you replace store.length with count on line 12, I just can't figure out why .length on the array wasn't enough. Anyone know?
store.lengthcan give odd responses; index should change consistently in theforEachloop. Try index ...