So, you’re trying to do a recursive function that will run with async functions in node? This example might be useful. We took the famous Fibonacci function and implemented the regular way and the async way. I wrote this post after finding a bug at a customer site that was related to async recursive functions. Here it is.

We will be using an Exress router for this example but any object will work:

var router = express.Router();

The “normal” way:

router.fib = function(n) { if(n <= 2) { return 1; } else { return this.fib(n - 1) + this.fib(n - 2); } };

Now the async function:

router.fibAsync = function(n) { return new Promise(function (resolve, reject) { if(n <= 2){ resolve(1); }else{ var sum = 0; router.fibAsync(n-1).then(function(res1){ sum += res1; router.fibAsync(n-2).then(function(res2){ sum += res2; resolve(sum); }); }); } }); };

As you can see, the function sums the values returned by the two recursive calls (fibAsync(n-1) and fibAsync(n-2)). The trick is to handle the returned values in the then() function and not as a traditional function where the value is returned to the caller. The problem with async recursive functions is that you can get into an never ending loop without going into a stack overflow (since each function runs on it’s own stack in the main node runtime loop). So the recursion can go forever in some cases.