NodeJSasynchronous和recursion

我已经广泛search,找不到似乎工作的答案。 我试过Q.deferred,async.series,async.each,我似乎无法得到这个吸盘工作:

这里是代码,这是有效的,但是,在recursion完成之前,“return subTree”会引发“树”导出。 我已经validation了recursion正在挖掘适当的。 我真的需要relaiveChildren的回报,等到recursion调用完成。

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

关于asynchronous模式的令人困惑的事情是,你不能返回一个实际的值,因为这还没有发生。 一旦asynchronous操作完成(callback),你可以传入一个函数来执行,或者你可以返回一个接受callback(promise)的对象,一旦操作用值parsingpromise,它就会执行callback。

 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); }); }); }; 
Interesting Posts