title: Exiting in node.js after recursive function is done
body: <p>I try to rewire my brain for async coding and I still I still seem to fail. Unfortunately I can't figure out how to do it properly in this case. Let me give an example:</p>
  
  <pre class="lang-js prettyprint-override"><code>var nconf = require('nconf');
  
   nconf.argv()
   .env();
  
   function runme(callback){
     var nummessages = nconf.get('SMS_MESSAGES');
     decodemessage(0, nummessages);
     callback();
   }
  
   function decodemessage(i, nummessages) {
    if( i &lt; nummessages ) {
      var message = 'SMS_'+(i+1)+'_TEXT';
      var number = 'SMS_'+(i+1)+'_NUMBER';
      console.log('number: '+number);
      console.log('message: '+message);
      console.log('message text: '+ nconf.get(message));
      console.log('message number: '+ nconf.get(number));
      decodemessage(i+1);
    }
  } 
  
  runme(function(){
    process.exit(0);
  });
  </code></pre>
  
  <p>This gets called by gammu-smsd which receives SMS messages and puts them into ENV vars and launches a script. This works fine as long as I run it on my own, return code seems to work as well. When I run it from gammu-smsd it fails and it looks like decodemessage is never executed. Some debug output shows that I do go into runme().</p>
  
  <p>My guess is that the callback in runme() gets executed before the recursive decodemessage() call is done. Am I right and if so can someone explain how I can do that properly?</p>
  
  <p>If you want to test run it like this:</p>
  
  <pre><code>node server.js --SMS_MESSAGES 2 --SMS_1_TEXT blabliblo --SMS_1_NUMBER=47796546546 --SMS_2_TEXT Iammessagetwo --SMS_2_NUMBER 12345678
  </code></pre>
  
  <p>Thanks</p>