问题描述
lastbalance
从未得到定义,因此getBalance函数从不执行其应有的功能.我以为这可能是异步性的问题,但是只有在第一个间隔之前是这样,对吧?有什么想法吗?
lastbalance
never get's defined and because of that the function getBalance never does what its supposed to. I thought this might be an issue with asynchronicity but that could only be the case before the first interval, right? Any ideas?
var lastbalance;
getBalance = function (lastbalance, callback){
btcclient.getBalance('*', 0, function(err, balance) {
if (err) return console.log(err);
if (lastbalance != balance || typeof lastbalance == 'undefined'){
console.log('Last Balance:' + lastbalance);
var lastbalance = balance;
updateCauses();
}
console.log('Balance:', balance);
if (typeof callback=='function') callback();
});
};
setInterval(getBalance, 2000, lastbalance);
推荐答案
两个问题.
1.:.您已将 lastbalance
定义为函数参数...,这在函数的上下文中创建了另一个 lastbalance
变量.取代了在外部作用域中声明的变量.
1.: You defined lastbalance
as a function parameter... which created another lastbalance
variable in the context of your function... which superseded the variable declared in the outer scope.
var lastbalance; // your outer variable
getBalance = function (lastbalance, callback) { // weeeee, another lastbalance
btcclient.getBalance('*', 0, function (err, balance) {
if (err) return console.log(err);
if (lastbalance != balance || typeof lastbalance == 'undefined') {
console.log('Last Balance:' + lastbalance);
var lastbalance = balance;
updateCauses();
}
console.log('Balance:', balance);
if (typeof callback == 'function') callback();
});
};
setInterval(getBalance, 2000, lastbalance); //passing lastbalance by value
2.::您使用了 var
在函数中声明了另一个 lastbalance
.不要那样做它导致了上述相同的问题.
2.: You used var
to declare yet another lastbalance
in your function. Don't do that; it caused the same issue described above.
var lastbalance; // your outer variable
getBalance = function (lastbalance, callback) {
btcclient.getBalance('*', 0, function (err, balance) {
if (err) return console.log(err);
if (lastbalance != balance || typeof lastbalance == 'undefined') {
console.log('Last Balance:' + lastbalance);
var lastbalance = balance; // here you create a local lastbalance.
// remove the var keyword to refer to
// the original lastbalance
updateCauses();
}
console.log('Balance:', balance);
if (typeof callback == 'function') callback();
});
};
setInterval(getBalance, 2000, lastbalance);
最后,您的代码应如下所示:
Finally, your code should look something like this:
var lastbalance;
getBalance = function (callback) { // remove parameter
btcclient.getBalance('*', 0, function (err, balance) {
if (err) return console.log(err);
if (lastbalance != balance || typeof lastbalance == 'undefined') {
console.log('Last Balance:' + lastbalance);
lastbalance = balance; // remove var
updateCauses();
}
console.log('Balance:', balance);
if (typeof callback == 'function') callback();
});
};
setInterval(getBalance, 2000); // remove argument
这篇关于为什么我的变量仍未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!