[英]nodeJs callbacks sharing variables?
So i have a problem with my nodejs code. 所以我的nodejs代码有问题。 I try to use this function to collect some information from some servers. 我尝试使用此功能从某些服务器收集一些信息。
Background: I have some server which are only control and monitoring stuff and some others which are for working. 背景:我有一些服务器仅用于控制和监视内容,而另一些则用于工作。 I call the functions in my code like this 我这样在代码中调用函数
// 1 callback
cmd.execute('getInformationScript ' + controlToken, function(queryResult){
exctractInfo(queryResult, function(result){
setcNodes(result)
});
});
//2 callback
cmd.execute('getInformationScript ' + imageToken, function(queryResult){
exctractInfo(queryResult, function(result){
setiNodes(result)
});
});
function exctractInfo(jsonString, callbackSucc){
var callbackArray = [];
var callbackResultArray = []
if(jsonString != null){
imageNodeArray = JSON.parse(jsonString);
for(imageNodes in imageNodeArray){
for(imageDetail in imageNodeArray[imageNodes]){
if ('name' in imageNodeArray[imageNodes][imageDetail]){
var name = imageNodeArray[imageNodes][imageDetail]['name'];
callbackArray.push(imageNodeArray[imageNodes][imageDetail])
// variable problem
cmd.execute('getInfomationFromServer.sh '+name+'', function(shellResult){
callbackResultArray.push(JSON.parse(shellResult));
if(callbackResultArray.length == callbackArray.length){
imageNodeArray[imageNodes] = mapCallbacks(callbackArray,callbackResultArray);
callbackSucc(imageNodeArray);
imageNodeArray = []
}
});
}
}
}
}
}
After some debugging i can see that my Arrays where i store my callbacks to count them seem to be overwritten. 经过一些调试后,我可以看到存储回调以计数它们的数组似乎被覆盖了。 So now a really stupid question ... why? 所以现在是一个非常愚蠢的问题……为什么? I allays tough every callback function has it own scope so why they overwriting each other. 我坚称每个回调函数都有自己的作用域,为什么它们要互相覆盖。
I really hope you can help me this is driving me crazy. 我真的希望您能帮助我,这使我发疯。
You didn't declare imageNodeArray
. 您没有声明imageNodeArray
。 In JavaScript, if you assign a value to an identifier without declaring that identifier via the var
keyword, then the variable is implicitly created in the global scope. 在JavaScript中,如果在不通过var
关键字声明标识符的情况下为标识符分配值,则该变量将在全局范围内隐式创建。
You need: 你需要:
var imageNodeArray = JSON.parse(jsonString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.