title: Promises with fs and bluebird
body: <p>I'm currently learning how to use promises in nodejs</p>
  
  <p>so my first challenge was to list files in a directory and then get the content of each with both steps using asynchronous functions. I came up with the following solution but have a strong feeling that this is not the most elegant way to do this, especially the first part where I am "turning" the asynchronous methods into promises
  </p>
  
  <pre class="lang-js prettyprint-override"><code>// purpose is to get the contents of all files in a directory
  // using the asynchronous methods fs.readdir() and fs.readFile()
  // and chaining them via Promises using the bluebird promise library [1]
  // [1] https://github.com/petkaantonov/bluebird 
  
  var Promise = require("bluebird");
  var fs = require("fs");
  var directory = "templates"
  
  // turn fs.readdir() into a Promise
  var getFiles = function(name) {
      var promise = Promise.pending();
  
      fs.readdir(directory, function(err, list) {
          promise.fulfill(list)
      })
  
      return promise.promise;
  }
  
  // turn fs.readFile() into a Promise
  var getContents = function(filename) {
      var promise = Promise.pending();
  
      fs.readFile(directory + "/" + filename, "utf8", function(err, content) {
          promise.fulfill(content)
      })
  
      return promise.promise
  }
  </code></pre>
  
  <p>Now chain both promises:</p>
  
  <pre class="lang-js prettyprint-override"><code>getFiles()    // returns Promise for directory listing 
  .then(function(list) {
      console.log("We got " + list)
      console.log("Now reading those files\n")
  
      // took me a while until i figured this out:
      var listOfPromises = list.map(getContents)
      return Promise.all(listOfPromises)
  
  })
  .then(function(content) {
      console.log("so this is what we got: ", content)
  })
  </code></pre>
  
  <p>As I wrote above, it returns the desired result, but I'm pretty sure there is a more elegant way to this.</p>