首页 > 解决方案 > Meteor递归方法调用导致无限循环

问题描述

给定树中的(父)节点,我需要检索 [1] 父级下的子级数加上父级子级下的子级加上父级子级的子级,依此类推 [2] [1] 中标记为“打开”的子级数.

我的测试数据有一个父母有两个孩子。我的方法——

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 
....

为什么在这种情况下第二次迭代会无限发生?这看起来是由于反应性,但我无法完全了解实际原因。

标签: javascriptmeteor

解决方案


很可能您只是var i在方法功能中缺少 a 。

如果不声明i为局部变量,则使用全局范围变量,每次调用方法时都会将其重新分配为 0。

顺便提一句:

  • 避免递归 Meteor 方法。您正在创建一个网络请求循环。如果您需要递归,请在专用函数中进行外部化。
  • 避免在助手中调用 Meteor 方法。改为使用ReactiveVar并仅在必要时进行调用,通常在 Blaze 模板生命周期挂钩(如 onCreated)或事件侦听器中。

推荐阅读