0

I'm already look in the What is the scope of variables in JavaScript? but it looks different. Variable which i will take are inside "function->for loops->function->end of if statement".

The code originally from net-ping

Here is the code :

var ping = require ("net-ping");
netping();

value = 0;

function netping() {
    var targets = ['8.8.8.8','8.8.4.4'];

    var session = ping.createSession ();

    for (var i = 0; i < targets.length; i++) {
        session.pingHost (targets[i], function (error, target, sent, rcvd) {
            var ms = rcvd - sent;
            if (error)
                if (error instanceof ping.RequestTimedOutError)
                    console.log (target + ": timeout " + ms + " ms");
                else
                    console.log (target + ": " + error.toString () + " (ms="+ ms + ")");
            else
            value = target + ": " + ms + " ms";
            console.log(value);
            // output 
            // 8.8.4.4: 6 ms
            // 8.8.8.8: 7 ms
        });
    }
}

console.log(value); // output 0

module.exports = netping;

How can i get the variable value from function netping to show them outside the function?

Ras
  • 991
  • 3
  • 13
  • 24
  • [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – t.niese Feb 18 '18 at 07:14
  • What do you expect that `console.log(value);` should contain, instead of `0`? `8.8.4.4: 6 ms` or `8.8.8.8: 7 ms`? You write `value = target + ": " + ms + " ms"` so even if it would work, it could contain only one of them. – t.niese Feb 18 '18 at 07:19
  • @t.niese, maybe i must use array variable to store the value? in terminal, the value show two times. I think maybe because the value is in the for loops. – Ras Feb 18 '18 at 07:24

0 Answers0