I am learning node.js with learnyounode
.
I am having a problem with JUGGLING ASYNC
.
The problem is described as follows:
You are given three urls as command line arguments. You are supposed to make http.get()
calls to get data from these urls and then print them in the same order as their order in the list of arguments.
Here is my code:
var http = require('http')
var truecount = 0;
var printlist = []
for(var i = 2; i < process.argv.length; i++) {
http.get(process.argv[i], function(response) {
var printdata = "";
response.setEncoding('utf8');
response.on('data', function(data) {
printdata += data;
})
response.on('end', function() {
truecount += 1
printlist.push(printdata)
if(truecount == 3) {
printlist.forEach(function(item) {
console.log(item)
})
}
})
})
}
Here is the questions I do not understand:
I am trying to store the completed data in response.on('end', function(){})
for each url using a dictionary. However, I do not know how to get the url for that http.get()
. If I can do a local variable inside http.get()
, that would be great but I think whenever I declare a variable as var url
, it will always point to the last url. Since it is global and it keeps updating through the loop. What is the best way for me to store those completed data as the value with the key equal to the url?