harry4
harry4

Reputation: 189

Get the correct loop value during callbacks

I am trying to poll multiple sites but when I try to print the array index it doesn't return the true index.

   var request = require('request');
var opt=['https://dev.twitter.com','https://developer.foursquare.com/','https://developers.facebook.com'];
function req()
{
for(i=0;i<opt.length;i++)
{

request(opt[i], function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log("Yes "+i)
  }
  else
    console.log("No");
})
}
}
setInterval(req,3000);

Whats the issue?

Upvotes: 1

Views: 54

Answers (1)

Manuras
Manuras

Reputation: 506

You are doing an asynchronous function call in a loop. This means the loop will continue while the request is being processed and will result in a wrong loop index.

If you want to get the correct index you have to either make the function call synchronous or you have to control the flow of your functions.

You can do this with the module async

Here an example.

var request = require('request')
 , async = require('async');

var opt = ['https://dev.twitter.com','https://developer.foursquare.com/','https://developers.facebook.com'];

function req() {

    var count = 0;

    // Use async to loop each opt value in series
    async.eachSeries(opt, function(entry, callback) {
        count++;

        request(entry, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log('Yes ' + count)
            }
            else {
                console.log('No');
            }

            callback(); 
        });
    }, function(err) {
         console.log('We are done!');
    });
}

setInterval(req,3000);

Upvotes: 2

Related Questions