我有一个数据库,其中父记录可以有无限个子级。以下简化的记录说明:
id:0,父级:空
id:1,父母:0
id:2,父母:0
id:3,父母:2
我已经尝试了好几个星期了,在node / express中编写一个递归函数,该函数生成一个表示此记录树的javascript对象,直到完成后才返回。只要包含超时,我就可以做到这一点,但这显然不是最佳选择。
这是我最近的尝试:
var getChildren = function (parent, callback) {
const query = "SELECT ID, ParentID, NULL AS Children FROM myTable WHERE "ParentID = '" + parent.ID + "'";
db.doQuery (query, function (err, results) {
if(err) {
callback (true);
} else {
if (results.length == 0) callback (false, parent); // We didn't find any children so we end the recursion
parent.Children = results; // Each time we get a result set we need to add that set to our Children property
// Iterate through our result set to find the next layer of children
var i = 0;
async.whilst (
function () { return i < results.length },
function (callback) {
i++;
getChildren(parent.Children[i - 1], function (err, results) {
if (err) callback (true);
})
},
callback (false, parent)
);
}
})
}
简而言之,这是一个递归例程,该例程从数据库中读取所有子项作为记录。它将此结果集添加到对象属性“ Children”,然后对其进行迭代,并对每个结果进行递归调用以查找该记录的更多子项。最终返回的JSON如下所示:
{
"ID": "000000000",
"ParentID": null,
"Children": [
{
"ID": "000000001",
"ParentID": "000000000",
"Children": null
},
{
"ID": "000000002",
"ParentID": "000000000",
"Children": [
{
"ID": "000000003",
"ParentID": "000000002",
"Children": null
}
]
}
]
}
您可能已经知道,实际上发生的是上述代码仅返回第一级子级,直到我在调用函数中设置了超时时间为止。我尝试了几个异步函数,尝试了超时,尝试使用自己的带有回调的递归函数重写循环,但我终生无法正常工作。我知道问题在于我只是无法绕过一些异步魔术,这将帮助我确定实际的递归何时完全完成并回调到调用函数。
在这种情况下,我必须跟踪自己调用的递归级别,然后在使用最终回调之前,在回调时对其进行递减计数吗?
任何见识将不胜感激。