将变量传递到node.js函数中

Pass variables into node.js function

本文关键字:js 函数 node 变量      更新时间:2023-09-26

我正试图将一个额外的变量(设备名)传递到session.pingHost中,这样只有在ping返回响应后,我才能运行另一个需要该变量的函数(someOtherFunction)。当前someOtherFunction接收未定义的设备名称。

我该如何做到这一点?有更好的方法吗?

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);
    });
}

使用回调是对pingDevice(包含devicename参数)调用上下文的闭包这一事实来执行此操作的方式完全是标准的、正常的做法。你可以做你正在做的事情,给定显示的代码,这就是我要做的

另一种方法是使用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创建一个新函数,当被调用时,该函数将使用特定的this值(我们在这里不使用该值,因此使用null)和您给bind的任何参数,然后是调用新函数时使用的参数。

但我认为这里没有任何必要。您需要或想要bind的唯一真正原因是,您是否希望在创建函数时获取devicename的值(因为它可能会更改)。


有一个无关的问题:您正成为隐式全局变量的恐怖的牺牲品,因为您没有声明pingresult变量。一定要在适当的上下文中声明变量。