Promises with fs and bluebird

前端 未结 1 823
独厮守ぢ
独厮守ぢ 2021-02-01 20:27

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

相关标签:
1条回答
  • 2021-02-01 20:53

    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.

    0 讨论(0)
提交回复
热议问题