javascript - 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
....
为什么在这种情况下第二次迭代会无限发生?这看起来是由于反应性,但我无法完全了解实际原因。
解决方案
很可能您只是var i
在方法功能中缺少 a 。
如果不声明i
为局部变量,则使用全局范围变量,每次调用方法时都会将其重新分配为 0。
顺便提一句:
- 避免递归 Meteor 方法。您正在创建一个网络请求循环。如果您需要递归,请在专用函数中进行外部化。
- 避免在助手中调用 Meteor 方法。改为使用
ReactiveVar
并仅在必要时进行调用,通常在 Blaze 模板生命周期挂钩(如 onCreated)或事件侦听器中。
推荐阅读
- python - 使用属性类型创建描述符时出现递归错误
- python - 如何更新 tkinter 消息
- java - 分配 Set 中的所有值
到地图 有溪流 - java - 网页视图中的 HTML Iframe 视频未播放
- c++ - 除非在终端中运行,否则 C++ 程序不会写入 /dev/stdout
- php - Ajax 在应该出错的时候总是成功
- jquery - 通过IE11查找jQuery脚本
- php - Apache2 mod_rewrite 不适用于嵌套文件夹
- php - Redis 处理 PHP 会话的问题
- intellij-plugin - Intellij Compound 和 Multirun 插件的限制和挑战