title: Adding to an array with an asynchronous function
body: <p>assume I have an array of files, file_urls, I want to parse through and add the results to a result array:</p>
  
  <pre><code>var requestImageSize = require('request-image-size');
  
  function parse_file(file) {
      return new Promise(function(resolve, reject) {
          /*this is an asynchronous function from an external library,
           it returns attributes about the file such as its size and dimensions
          */
          requestImageSize(file).then(function(result) { 
              resolve(result);            
          }
          .catch(function(err) {
              reject(err);
          });   
      })
  }
  var results = [];
  var promise;
  
  //assume file_urls is already populated with strings of urls to files
  file_urls.each(function(index, elem) {
      //if it's the last element then return the promise so we can return the final results at the end
      if (index == file_urls.length-1) {
          promise = parse_file(this);
      }
      //otherwise process the promise
      else {
          parse_file(this).then(function(result) {
              results.push(result);
          }
      }
  });
  
  //add the final element and return the final results
  promise.then(function(result) { 
      results.push(result);
      return result;
  });
  </code></pre>
  
  <p>Since parse_file returns a promise and I'm iterating through many promises, how do I ensure that the results array has the correct number (and possibly order) of elements?</p>
  
  <p>so far in my project it is returning an erratic number of elements, what should I do differently? </p>