Juan Sebastian Lozano Juan Sebastian Lozano - 6 months ago 21
Node.js Question

Javascript only running half of loop

I am using Node.js and I have a loop that looks like this:

var request = require('request');

for(var i = 0; i< some_number; i++){
console.log(i);
request( url.concat(i), function(error, response, body){
if(!error){console.log("ABC" + i)}
else{
console.log(error);
});

}


and it returns
0
to
some_number-1
before running
request
, and I'm not sure what's going on. I am using the request module.

Answer

When you make a request, it takes time to return, but the loop does not wait for it, it keeps going. This asynchronous nature is one of Javascript main principles.

If you want to wait for each request before continuing the loop, maybe try something like this:

function iterator(i) {
  if (i < some_number) {
    request(url.concat(i), function(err, response, body) {
      if (err) console.log(err);
      iterator(i + 1);
    });
  }
}
// Kick off the loop
iterator(0);