I have a javascript function that resolves a tree recursively. It has two flag variables that are set as false or true over the area of ββthe function itself, so if the flag is set to true once, while the walkTree function is recursive, this will be true for each recursion. On the other hand, the for loop may contain a return function, if necessary. I have a problem when there are too many recursions, I get an error message.
I would like to prevent this problem by making this recursive function asynchronous, I tried putting the sub walkTree () call inside the for loop in setTimeout, but the problem I have now is that the rest of the function (and may return the wrong value) before the rest of the asynchronous material is completed. So, how can I make this asynchronous while maintaining the correct value (rather than calling the top function in recursion)?
As you can see, the end of the function uses this flagB variable, which all calls share, and so we need to make sure that all recursive calls have been completed (and returned something) before the top one checks these conventions. Thanks!
var flagA = false; var flagB = false; var walkTree = function (n) { var sub; for (var i = 0; i < n.children.length; i++) { sub = walkTree(n.children[i]); if (sub === 'something-special') { return sub; } } var test = doSomethingWith(n); if (test === "something") { flagA = true; } if (test === "something-else") { flagB = true; } if (flagB === true) { return true; } if (test === "something-special") { return test; } else { return false; } }
source share