I'm new to javascript and node.js, so this might be basic javascript problem..
I'm solving this Juggling Async problem in LearnYouNode, but I don't know why my code isn't working.
my code:
const http = require('http');
var URLs = [process.argv[2], process.argv[3], process.argv[4]];
var strs = ["", "", ""];
var ctr = 0;
for(var i = 0; i < 3; i++){
http.get(URLs[i], (response) => {
response.setEncoding('utf8');
response.on('data', (data) => {
strs[i] += data;
});
response.on('end', () => {
ctr++;
if(ctr == 3){
console.log(strs[0]);
console.log(strs[1]);
console.log(strs[2]);
}
});
});
}
My code doesn't work, but this code does:
const http = require('http');
var URLs = [process.argv[2], process.argv[3], process.argv[4]];
var strs = ["", "", ""];
var ctr = 0;
function httpGet(i){
http.get(URLs[i], (response) => {
response.setEncoding('utf8');
response.on('data', (data) => {
strs[i] += data;
});
response.on('end', () => {
ctr++;
if(ctr == 3){
console.log(strs[0]);
console.log(strs[1]);
console.log(strs[2]);
}
});
});
}
for(var i = 0; i < 3; i++){
httpGet(i);
}
The code works only by making it as a function. Why is this?
EDIT: the problem is that the "strs[i] += data" part doesn't work!
- ACTUAL: ""
EXPECTED: "As cross as a turps how gutful of freckle. You little ripper gone walkabout mate you little ripper khe sanh. "
ACTUAL: ""
EXPECTED: "As dry as a milk bar when mad as a ambo. Stands out like a stickybeak my lets get some larrikin. He hasn't got a budgie smugglers and stands out like a show pony. "
ACTUAL: ""
EXPECTED: "You little ripper cockie where we're going digger. Grab us a bush oyster heaps you little ripper dero. Lets get some apples mate gutful of compo. "
ACTUAL: ""
- EXPECTED: ""