I have a complex recursive function in Node.js, which for the sake of this question I simplified to the following:
function sum(tree) {
if (!tree) return 0;
var sumLeft = sum(tree.left);
var sumRight = sum(tree.right);
return sumLeft + tree.val + sumRight;
}
var exampleTree = {
val: 3,
right: { val: 4 },
left: { val: 5,
right: {val: 6},
left: {val: 7}
}
}
console.log(sum(exampleTree)); // returns 25 = 3+4+5+6+7
Now I want to convert the function "sum" to an asynchronous function:
function sumAsync(tree, callback) {
// ???
}
But, since the function now doesn't return a value, I don't know how to get the values sumRight and sumLeft and combine them.
One possible option is to totally rewrite the algorithm such that it is iterative and not recursive (as suggested in this question: how to make this synchronous recursive function asynchronous). But, in many cases this might be very complicated and make the entire program unreadable. Is there a solution that keeps the simple structure of the recursive function, while making it asynchronous?
NOTE: My problem is not to sum the values in a tree... the tree-sum function is only a Minimal Working Example.
EDIT: Based on vkurchatkin's answer and comment, I decided to use async.parallel. This is the result:
var async = require("async");
function sumAsync (tree, callback) {
if (!tree) return setImmediate(callback.bind(null, null, 0));
async.parallel([
sumAsync.bind(this, tree.left),
sumAsync.bind(this, tree.right),
],
function(err, results) {
callback(err, tree.val+results[0]+results[1]);
});
}
sumAsync(exampleTree, function(err, result) {
console.log(result); // prints 25
});