[英]Meteor recursive method call causes infinite loop
給定樹中的(父)節點,我需要檢索[1]父項下的孩子數,再加上父級孩子的下子再加上父級孩子的子項,依此類推[2]從[1]中標記為“ OPEN”的孩子數。
我的測試數據有一個父母,其中有兩個孩子。 我的方法-
Meteor.methods({
...
'getSubCounts': function(selectedNodeId){
var children = ItemList.find({"parent.parentid": selectedNodeId}).fetch();
var numChildren = children.length;
console.log("Number of children of " + selectedNodeId + ": " + numChildren);
var openChildrenCount = children.filter(function(row) {
return (row.status === "OPEN");
}).length;
for (i = 0; i < numChildren; i++) {
console.log("iterations for child " + i + ": " + children[i]._id);
Meteor.call('getSubCounts', children[i]._id, function(error, result) {
if(error) {
console.log("error occured during iteration " + error);
} else {
numChildren = numChildren + result.numChildren;
openChildrenCount = openChildrenCount + result.openChildrenCount;
}
});
}
return {numChildren: numChildren, openChildrenCount: openChildrenCount};
},
...
});
我在客戶端幫助程序中調用的-
'subcounts': function(){
if (this._id != null) {
Meteor.call('getSubCounts', this._id, function(error, result) {
if(error) {
// nothing
} else {
Session.set('subcountsdata', result)
}
});
從(瀏覽器)輸出中,它似乎對第一個子項按預期進行了迭代,但是第二個子項陷入了無限循環。 (請注意,父節點ID是8veHSdhXKjyFqYZtx
,子節點ID是iNXvZGaTK3RR6Pekj,C6WGaahHrPiWP7zGe
)
Number of children of 8veHSdhXKjyFqYZtx: 2
iterations for child 0: iNXvZGaTK3RR6Pekj
Number of children of iNXvZGaTK3RR6Pekj: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
....
為什么在這種情況下第二次迭代無限發生? 它似乎是由於反應性造成的,但我不太了解實際原因。
很可能您只是在方法函數中缺少var i
。
在不將i
聲明為局部變量的情況下,您使用了全局范圍變量,該變量在每次調用方法時都會重新分配為0。
順便說一句:
ReactiveVar
並僅在必要時進行呼叫,通常是在Blaze模板生命周期掛鈎(如onCreated)或事件偵聽器中進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.