title: NodeJS and asynchronous hell
body: <p>I just came to this awful situation where I have an array of strings each representing a possibly existing file (e.g. <code>var files = ['file1', 'file2', 'file3']</code>. I need to loop through these file names and try to see if it exists in the current directory, and if it does, stop looping and forget the rest of the remaining files. So basically I want to find the first existing file of those, and fallback to a hard-coded message if nothing was found.</p>
  
  <p>This is what I currently have:</p>
  
  <pre><code>var found = false;
  files.forEach(function(file) {
    if (found) return false;
  
    fs.readFileSync(path + file, function(err, data) {
      if (err) return;
  
      found = true;
      continueWithStuff();
    });
  });
  
  if (found === false) {
    // Handle this scenario.
  }
  </code></pre>
  
  <p>This is bad. It's blocking (readFileSync) thus it's slow.</p>
  
  <p>I can't just supply callback methods for <code>fs.readFile</code>, it's not that simple because I need to take the first found item... and the callbacks may be called at any random order. I think one way would be to have a callback that increases a counter and keeps a list of found/not found information and when it reaches the <code>files.length</code> count, then it checks through the found/not found info and decides what to do next.</p>
  
  <p>This is painful. I do see the performance greatness in evented IO, but this is unacceptable. What choices do I have?</p>