Friday 2 June 2017

learnyounode #9 - juggling async and the difference between forEach and for loop

When I have the code:

const http = require("http");
var url1 = process.argv[2];
var url2 = process.argv[3];
var url3 = process.argv[4];
var urls = [url1, url2, url3];
var result = [];
var count = 0;

function collectAll() {
  for(var i = 0; i < urls.length; i++) {
    http.get(urls[i], (response) => {
      var alldata = "";
      response.setEncoding("utf8");
      response.on("data", (data) => {
        alldata += data;
      });
      response.on("end", () => {        
        result[i] = alldata;
        count++;
        if(count == 3) {
            for(var j = 0; j < result.length; j++) {
                console.log(result[j]);
            }
        }
      });
    }).on("error", console.error);
  }
}

collectAll();

And I run the learnyounode verify command, I get undefined whenever it expected a string and then some string when it expected an empty string.

When I change the above code so that the main for loop is replaced with: urls.forEach(function(url, i) {//previous code inside for loop}); I get the correct answer. Is there a reason why the forEach loop worked where the for loop did not. What's going on here?



via Dak Song

No comments:

Post a Comment