首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带fs和bluebird的承诺

带fs和bluebird的承诺
EN

Stack Overflow用户
提问于 2013-10-17 22:16:18
回答 1查看 15.5K关注 0票数 19

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

因此,我的第一个挑战是列出一个目录中的文件,然后使用异步函数通过两个步骤获取每个文件的内容。我想出了下面的解决方案,但我有一种强烈的感觉,那就是这不是做这件事最优雅的方式,特别是在我将异步方法“转换”成promises的第一部分

代码语言:javascript
复制
// 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
}

现在将这两个承诺链接起来:

代码语言:javascript
复制
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)
})

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-21 05:38:24

使用generic promisification.map方法可以使代码变得更短:

代码语言:javascript
复制
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)
});

事实上,你可以进一步调整它,因为函数不再发挥其作用了:

代码语言:javascript
复制
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应该是您赖以生存的方法-它真的很强大,因为它适用于任何事情,从一系列承诺映射到进一步的承诺,再到中间直接值的任何组合。

票数 46
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19429193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档