我进行了大量搜索,但找不到似乎有效的答案。我已经尝试过 Q.deferred、async.series、async.each,我似乎无法让这个傻瓜工作:
这是代码,这有效,但是,在递归完成之前,“返回子树”会触发“树”导出。我已经验证了递归正在适本地挖掘。我确实需要 recuriveChildren 的返回来等待递归调用完成。
exports.tree = function(req, res) {
var tree = {
'name': 'New Account'
};
var methods = {};
methods.recursiveChildren = function(path) {
var subTree = {
'name': path.field.label+":"+path.match+":"+path.value,
'id': path._id,
'parent': path.parent,
'children': []
}
Path.find({parent:path._id}).sort({date_created:1}).exec(function (err,childpaths) {
for ( var z in childpaths ) {
var tmpTree = methods.recursiveChildren(childpaths[z]);
subTree.children.push(tmpTree);
}
});
return subTree;
}
Path.find({parent:null}).sort({date_created:1}).exec(function (err,paths) {
tree.children = [];
for ( var x in paths ) {
var tmpTree = methods.recursiveChildren(paths[x]);
tree.children.push(tmpTree);
}
res.jsonp(tree);
});
};
最佳答案
关于异步模式的令人困惑的事情是您无法返回实际值,因为这还没有发生。您可以传入一个在异步操作完成后执行的函数(回调),也可以返回一个接受回调的对象( promise ),一旦操作用值解析 promise ,该对象就会执行回调。
exports.tree = function(req, res) {
var tree = {
'name': 'New Account'
};
var methods = {};
methods.recursiveChildren = function(path) {
var subTree = {
'name': path.field.label + ":" + path.match + ":" + path.value,
'id': path._id,
'parent': path.parent,
'children': []
}
return new Promise(function(resolve, reject) {
Path.find({
parent: path._id
}).sort({
date_created: 1
}).exec(function(err, childpaths) {
Promise
.all(childpaths.map(function(childpath) {
/* collect a promise for each child path this returns a promise */
return methods.recursiveChildren(childpath);
}))
.then(function(resolvedPaths) {
subtree.children = resolvedPaths;
/* the top level promise is fulfilled with the subtree */
resolve(subTree);
});
});
});
}
Path.find({
parent: null
}).sort({
date_created: 1
}).exec(function(err, paths) {
Promise.all(paths.map(function(path) {
return methods.recursiveChildren(path);
})).then(function(resolvedPaths) {
tree.paths = resolvedPaths;
res.jsonp(tree);
});
});
};
关于node.js - NodeJS 异步和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869910/