简体   繁体   中英

Pass variables into node.js function

I am trying to pass an additional variable (devicename) into session.pingHost so that only once the ping has returned a response do I run another function (someOtherFunction) which requires the variable. Currently someOtherFunction receives devicename as undefined.

How would I accomplish this? Is there a better way of doing it?

var ping = require("net-ping");
var pingresult = '';

pingDevice('xxx.xxx.xxx.xxx', 'My Device');

function pingDevice(ipaddress, devicename){

    var options = {
        retries: 1,
        timeout: 2000
    };

    var session = ping.createSession (options);

    session.pingHost (ipaddress, function (error, target) {

        if (error) {
            console.log (target + ": ping FAIL");
            pingresult = '0';
        } else {
            console.log (target + ": ping OK");
            pingresult = '1';
        }

        someOtherFunction(pingresult,devicename);

    });
}

The way you're doing it, using the fact that the callback is a closure over the context of the call to pingDevice (which contains the devicename argument), is entirely standard, normal practice. You can do exactly what you're doing, and given the code shown, it's what I would do.

Another way to do it is to use Function#bind :

session.pingHost (ipaddress, function (devicename, error, target) {
// ------------------------------------^^^^^^^^^^

    if (error) {
        console.log (target + ": ping FAIL");
        pingresult = '0';
    } else {
        console.log (target + ": ping OK");
        pingresult = '1';
    }

    someOtherFunction(pingresult,devicename);

}.bind(null, devicename));
//^^^^^^^^^^^^^^^^^^^^^^

Function#bind creates a new function that, when called, will call the original with a specific this value (we're not using that here, hence the null ) and any arguments you give bind , followed by the arguments the new function was called with.

But I don't see any need for that here. The only real reason you'd need or want bind would be if you wanted to grab the value of devicename as of when you created the function (because it might change).


There is an unrelated problem: You're falling prey to The Horror of Implicit Globals because you don't declare your pingresult variable. Always be sure to declare your variables, in the appropriate context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM