title: Returning a value from an asynchronous recursive function
body: <p>I have a complex recursive function in Node.js, which for the sake of this question I simplified to the following:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Now I want to convert the function "sum" to an asynchronous function:</p>
  
  <pre><code>function sumAsync(tree, callback) {
      // ???
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>One possible option is to totally rewrite the algorithm such that it is iterative and not recursive (as suggested in this question: <a href="https://stackoverflow.com/questions/8126178/how-to-make-this-synchronous-recursive-function-asynchronous?rq=1">how to make this synchronous recursive function asynchronous</a>). 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?</p>
  
  <p>NOTE: My problem is not to sum the values in a tree... the tree-sum function is only a Minimal Working Example.</p>
  
  <p>EDIT: Based on vkurchatkin's answer and comment, I decided to use async.parallel. This is the result:</p>
  
  <pre><code>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
  });
  </code></pre>