I\'m currently learning how to use promises in nodejs
so my first challenge was to list files in a directory and then get the content of each with both steps using async
The code can be made shorter by using generic promisification and the .map method:
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for you
var directory = "templates";
var getFiles = function () {
return fs.readdirAsync(directory);
};
var getContent = function (filename) {
return fs.readFileAsync(directory + "/" + filename, "utf8");
};
getFiles().map(function (filename) {
return getContent(filename);
}).then(function (content) {
console.log("so this is what we got: ", content)
});
In fact you could trim this even further since the functions are not pulling their weight anymore:
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for you
var directory = "templates";
fs.readdirAsync(directory).map(function (filename) {
return fs.readFileAsync(directory + "/" + filename, "utf8");
}).then(function (content) {
console.log("so this is what we got: ", content)
});
.map
should be your bread and butter method when working with collections - it is really powerful as it works for anything from a promise for an array of promises that maps to further promises to any mix of direct values in-between.