0

I am undertaking the learnyounode tutorial at nodeschool.io and have reached the "Juggling Async" task. I've got the following code:

var http=require('http');
var urls = process.argv.slice(2);

var body=[];
var urlstream = [];
var arraySize=urls.length;

for (var i=0; i<arraySize; i++) { 

console.log(getData(i));
}

function getData(i) {
//console.log(urls[i]);
  urlstream[i] = http.get(urls[i], function(response) {
    response.on('data', function(d) {
      body[i]+=d.toString('UTF-8');
    })
    response.on('end', function() {
      //console.log(body[i]);
      return body[i];
    })
    response.on("error", function(err) {
      console.log("error: " + err);
    })
  });
}

When I pass the script three URLs, it returns three "undefined" messages; however, when I pass the following script the same three URLs, I get expected data back:

var http=require('http');
var urls = process.argv.slice(2);

var body=[];
var urlstream = [];
var arraySize=urls.length;

for (var i=0; i<arraySize; i++) {
  urlstream[i] = http.get(urls[i], function(response) {
    response.on('data', function(d) {
      body[i]+=d.toString('UTF-8');
    })
    response.on('end', function() {
     console.log(body[i]);
    })
    response.on("error", function(err) {
      console.log("error: " + err);
    })
  });
}

Whilst I don't think that I am necessarily going to complete the tutorial with the approach I've taken, please could someone explain why the latter code works, but when I try to make it into a function and return an element from the 'body' array, it doesn't return data. Is it a scoping issue? I am new to Javascript and a clear explanation would be really helpful.

Ooberdan
  • 720
  • 1
  • 6
  • 18

0 Answers0