0

I am writing a very simple script in JavaScript, It is supposed to ping every IP in a subnet and if the IP responds it puts it in one array and if it does not respond it puts it in a different array.

My problem is, when i try to call the array after the loop filling the array it's empty, but if i call the array during the loop it is filling.

Here is my code:

var ping = require ('ping');
var targets = [];
var avail = [];
var unAvail = [];

var i = 0;
while (i < 255){
        targets.push('100.73.1.'+i);
        i++;
}
targets.forEach(function(target){
        ping.sys.probe(target, function(isAlive){
                if (isAlive){
                        unAvail.push(target);
                        console.log(unAvail);
                }else{
                        avail.push(target);
                }
        });
});

unAvail.forEach(function(ip){
        console.log(ip);
});

edit: The ping it is using is npm ping https://www.npmjs.com/package/ping

edit: Modified the code to run with a promise.

var ping = require ('ping');
var targets = [];
var avail = [];
var unAvail = [];

var i = 0;
while (i < 255){
        targets.push('100.73.1.'+i);
        i++;
}
targets.forEach(function(target){
      ping.promise.probe(target)
                .then(function(isAlive){
                        if (isAlive){
                                unAvail.push(target);
                                //console.log(unAvail);
                        }else{
                                avail.push(target);
                        }
                });
});
console.log(unAvail) 
Ezekiel Hammond
  • 115
  • 1
  • 13
  • 2
    The response from ping are async. You will have to wait till all responses are available. For this you can take help of promises. – Amal Dec 19 '17 at 10:00
  • @Amal even running it with a promise i get the same result. – Ezekiel Hammond Dec 19 '17 at 10:10
  • The promise will resolve *after* you are trying to `console.log` the result. It is the `console.log` that you need to promisify. – deceze Dec 19 '17 at 10:22

0 Answers0