title: Asynchronous for loop: how do I make the for loop wait for function to finish?
body: <p>I'm racking my brain trying to figure out how to sequence this / place callbacks to get what I need.</p>
  
  <p>I have a loop that checks for the existence of files. I'd like it to callback when it's done, but the <code>for</code> loop and the callback finish before the "fs.open" finishes... typical asynchronous problem.</p>
  
  <p>I am using <strong>node v0.10.29</strong>, <strong>express v3.14.0</strong>, and am looking at using the "<strong><a href="https://github.com/caolan/async" rel="nofollow">async</a></strong>" library, but again, just can't figure out the logic that I need...</p>
  
  <p>Here is what I have:</p>
  
  <h1>Input</h1>
  
  <pre><code>function checkForAllFiles(callback)
  {
      var requiredFiles = [];
      requiredFiles[requiredFiles.length] = "../Client/database/one.js";
      requiredFiles[requiredFiles.length] = "../Client/database/two.dat";
      requiredFiles[requiredFiles.length] = "../Client/database/three.xml";
      requiredFiles[requiredFiles.length] = "../Client/database/four.dat";
      requiredFiles[requiredFiles.length] = "../Client/database/five.dat";
      requiredFiles[requiredFiles.length] = "../Client/database/six.xml";
  
      var missingFiles = [];
      for(var r=0; r&lt;requiredFiles.length; r++)
      {
          fs.open(requiredFiles[r], 'r', function(err, fd){
              if(err)
              {
                  missingFiles[missingFiles.length] = err.path;
                  console.log("found missing file = ", err.path);
              }
          });
          console.log("r = ", r);
      }
      console.log("sending callback: ", missingFiles);
      callback(missingFiles);
  }
  </code></pre>
  
  <h1>Output</h1>
  
  <pre><code>0
  1
  2
  3
  4
  5
  sending callback: []
  found missing file: ../Client/database/three.xml
  </code></pre>
  
  <h1>Desired Output</h1>
  
  <pre><code>0
  1
  found missing file: ../Client/database/three.xml
  2
  3
  4
  5
  sending callback: ["../Client/database/three.xml"]
  </code></pre>