Promises With Fs And Bluebird
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 asynchronous func
Solution 1:
The code can be made shorter by using generic promisification and the .map
method:
varPromise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for youvar directory = "templates";
var getFiles = function () {
return fs.readdirAsync(directory);
};
var getContent = function (filename) {
return fs.readFileAsync(directory + "/" + filename, "utf8");
};
getFiles().map(function (filename) {
returngetContent(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:
varPromise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for youvar 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.
Post a Comment for "Promises With Fs And Bluebird"