javascript 对 fs 和 bluebird 的承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19429193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:33:45  来源:igfitidea点击:

Promises with fs and bluebird

javascriptnode.jsasynchronousfsbluebird

提问by Henrik

I'm currently learning how to use promises in nodejs

我目前正在学习如何在 nodejs 中使用 promise

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

所以我的第一个挑战是列出目录中的文件,然后使用异步函数通过两个步骤获取每个文件的内容。我想出了以下解决方案,但有一种强烈的感觉,这不是最优雅的方法,尤其是我将异步方法“转换”为承诺的第一部分

// 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
}

Now chain both promises:

现在链接两个承诺:

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)
})

As I wrote above, it returns the desired result, but I'm pretty sure there is a more elegant way to this.

正如我上面写的,它返回所需的结果,但我很确定有一种更优雅的方法。

回答by Esailija

The code can be made shorter by using generic promisificationand the .mapmethod:

可以通过使用泛型 promisification.map方法来缩短代码:

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)
});

.mapshould 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.

.map应该是处理集合时的基本方法——它真的很强大,因为它适用于从一系列承诺映射到进一步承诺到中间直接值的任何组合的任何事情。