Meteor recursive method call causes infinite loop

Given a (parent) node in a tree, i need to retrieve [1] Number of children under parent plus under the parent's children plus parent's children's children and so on [2] Number of children from [1] that are marked "OPEN".

My test data has one parent which has two children. My method -

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};
},


});

Which i am invoking in a client-side helper -

‘subcounts’: function(){
if (this._id != null) {
Meteor.call(‘getSubCounts’, this._id, function(error, result) {
if(error) {
// nothing
} else {
Session.set(‘subcountsdata’, result)
}
});

From the (browser) output, It appears to iterate as expected for the first child but the second one is stuck in an infinite loop. (Note that the parent node id is 8veHSdhXKjyFqYZtx and the children ids are 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

Why does the second iteration occur infinitely in this case? It looks to be due to the reactivity but i can’t quite get to the actual reason.

#javascript #meteor

3 Likes3.00 GEEK