title: How to write a node.js function that waits for an event to fire before 'returning'?
body: <p>I have a node application that is <em>not</em> a web application - it completes a series of asynchronous tasks before returning 1. Immediately before returning, the results of the program are printed to the console.</p>
  
  <p>How do I make sure all the asynchronous work is completed before returning? I was able to achieve something similar to this in a web application by making sure all tasks we completed before calling res.end(), but I haven't any equivalent for a final 'event' to call before letting a script return.</p>
  
  <p>See below for my (broken) function currently, attempting to wait until callStack is empty. I just discovered that this is a kind of nonsensical approach because node waits for processHub to complete before entering any of the asynchronous functions called in processObjWithRef.</p>
  
  <pre><code>function processHub(hubFileContents){
      var callStack = [];
      var myNewObj = {};
      processObjWithRef(samplePayload, myNewObj, callStack);
      while(callStack.length&gt;0){
          //do nothing
      }
      return 1
  }
  </code></pre>
  
  <p>Note: I have tried many times previously to achieve this kind of behavior with libraries like async (see my related question at <a href="https://stackoverflow.com/questions/9884418/how-can-i-make-this-call-to-request-in-nodejs-synchronous">How can I make this call to request in nodejs synchronous?</a>) so please take the answer and comments there into account before suggesting any answers based on 'just use asynch'.</p>