title: Implemented nested async calls in node.js
body: <p>Node noobie here. After doing a lot of searching and reading a lot of articles, posts, and Stackoverflow discussions, I remain stuck when implementing nested async calls in node.js. Here is the scenario I'm trying to implement:</p>
  
  <p>My code receives an event to open the third party CSV file. Once the file is opened, the content must be validated. If the data is valid, it gets persisted to the backend data store. Any exception to the validation rules must be stored in a separate error log on the back end.</p>
  
  <p>I've modularized the solution into separate functions: one function to open the file, the next function to validate the contents of the file, the next function to persist the content, and finally last function to persist eventual errors generated by the validation function.</p>
  
  <p>Each of these functions incurs certain latency, which necessitates using callbacks. But because the nesting of the callbacks can go a few levels deep, I've tried to keep my code shallow and to separate concerns and compartmentalize the logic in separate modules/functions. Now when I'm trying to string them together, I am failing at implementing correct callback logic.</p>
  
  <p>For example, my top level module looks something like this:</p>
  
  <pre><code>module.exports = {
    openFile: (filePath) =&gt; {
      // code to open file and load the content
      readAndParseFile(fileContent, validateAndReturnStatus);
    }
  }
  
  function readAndParseFile(fileContent, next) {
    // code to parse file content into rows of data
    next(rows, persistValues);
  }
  
  function validateAndReturnStatus(rows, next) {
    // code to validate
    if(valid) {
      persistValues(row, sendResponse);
    }
  }
  
  function persistValues(row, next) {
    //code to persist validated data
    next('success');
  }
  
  function sendResponse(status) {
    console.log(status);
  }
  </code></pre>
  
  <p>Above is a very simplified pseudo-code, but I hope it illustrates my intention. My question is: what is the most reliable, correct way to nest functions that are unavoidably latent and make sure that the batch process is waiting on the correct status at the end of the processing?</p>
  
  <p>Thanks.</p>