0

I have this code where I want to go trough different links and get information about the HTML code inside it.

var request = require("request");
var components = ["componentName1", "componentName2", "componentName3"];

for(let i = 0; i < components.length; i++) {

request('http://www.examplesite.com/' + components[i] + '/tags/', function (err, resp, body) {

    if (!err && resp.statusCode == 200) {

        var versions = body.match(/(\d+\.)(\d+\.)(\*|\d+)/g);
        console.log(versions);

    } else {
        console.log("Error: " + resp.statusCode);
        if(err) console.log(err);
    }

});

}

Problem is that loop finishes before all the requests are completed, so instead of getting information about different html pages, the loop collects information about one page times components.length. I understand this is most probably issue with function executed asynchronously and I've gone trough documentation, tried promises and counters and still can't make it to work. Am I missing something?

  • This type of question is answered before, [https://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript](https://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript) – Jay Surya Nov 05 '18 at 10:03
  • i don’t think there’s a problem with this code, it’s probably how you use it – mihai Nov 05 '18 at 19:25

0 Answers0