我的全局作用域中有一个函数,用于侦听 FB 引用上的值。
function updateCredits(userID){
var userRef = database.ref('users/' + userID);
userRef.on('value', function(snapshot){
var userCredits = snapshot.val().credits;
console.log(userCredits);
console.log('account: ' + userID + " has " + userCredits + " credits");
var updatedCredits = userCredits + ANTE;
userRef.update({credits: updatedCredits});
console.log("now it has " + updatedCredits + ANTE);
});
}
articlesRef.on('child_added', function(data) {
var upVoteRef = database.ref('articles/' + data.key + '/upVotes/');
try {
var upVotersRef = database.ref('articles/' + data.key + '/upVoters/');
upVoteRef.on('value', function(childData){
upVotersRef.on('value', function(voterData){
var voterKeys = Object.keys(voterData.val());
for (var i=0; i<voterKeys.length; i++){
upVotersRef.child(voterKeys[i]).on('value', function(voterID){
console.log("trying with voter ID " + voterID.val());
updateCredits(voterID.val());
});
}
});
});
} catch(err){
console.log(err.message);
}
var downVoteRef = database.ref('articles/' + data.key + '/downVotes/');
downVoteRef.on('value', function(childData){
console.log(childData.val());
});
});
不知何故,当我加载页面时,这个函数显然被调用了数百或数千次。我将其记录到控制台:
account: HMHZ8Ga3UGhc2wSczHDuFL82FB02 has 1328.6999999997329 credits app.js:25:9
1328.6999999997329 app.js:24:9
1328.8999999997327 app.js:24:9
account: HMHZ8Ga3UGhc2wSczHDuFL82FB02 has 1328.8999999997327 credits app.js:25:9
1328.8999999997327 app.js:24:9
account: HMHZ8Ga3UGhc2wSczHDuFL82FB02 has 1328.8999999997327 credits app.js:25:9
1328.9999999997326 app.js:24:9
account: HMHZ8Ga3UGhc2wSczHDuFL82FB02 has 1328.9999999997326 credits app.js:25:9
1328.9999999997326 app.js:24:9
account: HMHZ8Ga3UGhc2wSczHDuFL82FB02 has 1328.9999999997326 credits ...
(如您所见,由于某种原因,同一个帐户被重复给予积分。我希望它仅在 upVote 上获得积分);
它继续与..
now it has 1330.09999999973160.1 app.js:28:9
now it has 1329.99999999973170.1 app.js:28:9
now it has 1329.89999999973180.1 app.js:28:9
now it has 1329.79999999973190.1 app.js:28:9
now it has 1329.6999999997320.1 app.js:28:9
...
最后是问题:
too much recursion[Learn More] firebase.js:293:781
我猜想 updateCredits 函数正在触发 upVoteRef 监听的事件,该事件又调用 updateCredits 函数并变成循环。我不知道如何避免这种情况。有任何想法吗?