title: Return values from an async function
body: <p>I'm very new to JS and Node. My confusion is how do I push the values from an async task to a array and then print the array once all the operations are done.</p>
  
  <p>My code is:</p>
  
  <pre><code>function movieNames(dirname) {
      return new Promise(function (resolve, reject) {
          dir.files(dirname, function (err, files) {
              if (err) {
                  reject(err)
              } else {
                  resolve(files)
              }
          })
      })
  }
  
  
  function movieMetadata(path) {
      return new Promise(function (resolve, reject) {
          probe(path, function (err, probeData) {
              if (err) {
                  reject(err)
              } else {
                  resolve(probeData)
              }
          })
      })
  }
  
  var movies = []
  movieNames('D:/Media').then(function (moviepaths) {
      moviepaths.forEach(function (moviepath) {
          movieMetadata(moviepath).then(function (movie) {
           //console.log(movie)
          movies.push(movie)
      }, function (error) {
          console.log(error)
      })
      })
  }, function (error) {
      console.log(error)
  }).then(function () {
      console.log(movies)
  })
  </code></pre>
  
  <p>When I run this code, it just prints the empty array '[]'.</p>
  
  <p>Also I run the following code: </p>
  
  <pre><code>var i=0;
  movieNames('D:/Media').then(function (moviepaths) {
      moviepaths.forEach(function (moviepath) {
          movieMetadata(moviepath).then(function (movie) {
           //console.log(movie)
          movies.push(movie)
          console.log(i++)
          // movies = movie
      }, function (error) {
          console.log(error)
      })
      })
  }, function (error) {
      console.log(error)
  }).then(function () {
      console.log(movies)
  })
  </code></pre>
  
  <p>Output is: node movieNames.js
  []
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
  12
  13
  14
  15
  16
  17
  18</p>
  
  <p>I cannot understand why console.log(movies) is getting executed before the console.log(i++). If i just get this fixed, the code should run fine i believe.</p>