2015-12-28 119 views
0

我想传递一个额外的变量(devicename)到session.pingHost,以便只有一次ping返回响应我运行另一个函数(someOtherFunction)需要变量。目前someOtherFunction接收devicename为undefined。将变量传递到node.js函数

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

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

    }); 
} 

回答

0

你这样做,用事实回调是一个闭包在调用的上下文来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的任何参数,随后是调用新函数的参数。

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


有一个无关问题:你堕入The Horror of Implicit Globals,因为你不声明你的pingresult变量。一定要确保在适当的上下文中声明变量。

+0

感谢您的回复。问题是,当我这样做,并打电话给其他功能,那么devicename是未定义的。即。没有传入session.pingHost。 – sardaukar81

+1

@ sardaukar81:'pingHost'中的'devicename'的值将完全取决于你如何调用'pingHost',你没有显示。假设你用正确的值作为第二个参数调用'pingHost',稍后将使用相同的值来调用'someOtherFunction'。 –

+0

嗨TJ:我已根据您的建议更新了我的问题。问题是session.pingHost是net-ping库的一部分,所以我不能在其中添加额外的参数。我无法弄清楚如何通过session.pingHost将devicename传递给其他函数。 – sardaukar81