NodeJS中的递归异步循环 [英] Recursive Async Looping in NodeJS

查看:50
本文介绍了NodeJS中的递归异步循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一个递归异步循环,以从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.

这里是伪代码:

var tracer = function(nodes){
  var promises [];

  nodes.forEach(function(node){

    // trace returns a promise ...
    var promise = builder.trace(node)
    promises.push(promise);

    promise.then(function(tree){

      // if we had children, get those
      if(tree.children.length){
        promises.push.apply(promises, tracer(tree.children));
      }
    });   

  });

  return promises;
};

RSVP.all(tracer(myArr)).then(function(allTrees){ ... });

但是我不能指望如何使它们全部正确解析并将结果返回到一个数组中.

but I can't put my finger on how to get them all to resolve correctly and returns the results in one array.

推荐答案

您不得在延迟的回调中对数组中的递归承诺进行 push .相反,您需要立即推送一个表示递归结果的Promise(使用那些延迟产生的Promise进行解析).幸运的是,您甚至可以从该 then 调用中准确地得到这一点.

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.

此外,我会将每个换成 map ,并立即在函数内部执行 RSVP.all ,以免期望呼叫者来解决这个问题.

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.

function tracer(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 those
      if (tree.children.length)
        return tracer(tree.children));
      else
        return node;// the leaf node itself
    });
    return recusivePromise; // which will resolve with the `tracer(…)` result
                            // or the leaf
  });
  return RSVP.all(promises);
}

tracer(myArr).then(function(allTrees){ … });

这篇关于NodeJS中的递归异步循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆