Javascript - 在net-ping函数中获取值

时间:2018-02-18 06:42:55

标签: javascript node.js variables global-variables

我已经查看了What is the scope of variables in JavaScript? 但它看起来不同。我将采取的变量位于“function-> for loops-> function-> end of if statement”。

最初来自net-ping

的代码

以下是代码:

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;

如何从函数netping中获取变量值以在函数外显示它们?

0 个答案:

没有答案