开发者

Recursive directory based callback - Node.js

开发者 https://www.devze.com 2023-04-04 19:41 出处:网络
I have a recursive function which does a sort of tree process where each call may call itself multiple times, I don\'t have any way of knowing how deep or wide it is. How do I run a callback once the

I have a recursive function which does a sort of tree process where each call may call itself multiple times, I don't have any way of knowing how deep or wide it is. How do I run a callback once the entire process has been completed?

I'm thinking of having s开发者_高级运维ome sort of object to pass about to do a count but not quite cracked it yet, i'm wondering if there is a known best/better way of doing this.


You could do something like:

function recurseTree(arg, callback) {
    var recurse = function(a) {
        if (someCondition) {
            recurse(a);
        }
    };
    recurse(arg);
    callback();
}

All of your actual recursive logic will go in the recurse function, and the callback will be called only after all recursion is finished.

EDIT:

Here is a simple implementation

function recursiveAlert(x, callback) {
    var recurse = function(y) {
        alert(y);
        if (y < 3) {
            recurse(y + 1);
        }
    }
    recurse(x);
    callback();
}

recursiveAlert(0, function() { alert('done'); });


what I needed to do is count the number of paths in each tree before calling the callback e.g.:

myFunction: function(tree) {
  var count = 0;
  finishCallback = function() {
    if (--count === 0){
       callback();
    };
  };

  recursion = function(subTree) {
    count = tree.paths.length;

    _.each(subTree.path, function(route) {
      count += subFolder.fileRefs.length;
      recursion(route, function() {
        finishCallback();
      });
    });
  };

  recursion(tree);
}

Perhaps the count should not be inside myFunction but recursion should have its own count, however this works. (i've not tested this example)

0

精彩评论

暂无评论...
验证码 换一张
取 消