Recursive Async Looping In Nodejs
I'm trying to do a recursive async loop to trace all the children of a particular object from a third-party lib in nodejs. Heres the pseudo code: var tracer = function(nodes){ va
Solution 1:
You must not push
the recursive promises on the array in the delayed callback. Instead, you'll need to push a promise that represents the recursive results (resolves with those delayed produced promises) right away. Luckily, you even get exactly that back from that then
call.
Additionally, I would swap out the each
for a map
, and do RSVP.all
immediately inside the function, for not expecting the caller to deal with that.
functiontracer(nodes){
var promises = nodes.map(function(node){
// trace returns a promise ...var promise = builder.trace(node)
var recusivePromise = promise.then(function(tree){
// if we had children, get thoseif (tree.children.length)
returntracer(tree.children));
elsereturn node;// the leaf node itself
});
return recusivePromise; // which will resolve with the `tracer(…)` result// or the leaf
});
returnRSVP.all(promises);
}
tracer(myArr).then(function(allTrees){ … });
Solution 2:
I ended up going with a counter type approach ...
var traceDeps = function(parents, cb){
var count = 0,
trees = [],
trace = function(nodes){
nodes.forEach(function(node){
count++;
builder.trace(node).then(function(tree){
trees.push(tree);
if(tree.children.length){
trace(tree.children);
}
count--;
if (count === 0) cb(trees);
});
});
};
trace(parents);
};
traceDeps(myArr, function(trees){ ... });
Post a Comment for "Recursive Async Looping In Nodejs"