与fs和蓝鸟的承诺

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

所以我的第一个挑战是列出目录中的文件,然后使用asynchronousfunction获取每个步骤的内容。 我提出了以下的解决scheme,但有一种强烈的感觉,这并不是最优雅的方式,特别是第一部分,我将asynchronous方法“转向”承诺

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

现在连锁的承诺:

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

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

通过使用通用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) }); 

事实上,你可以进一步修剪这个function,因为function已经不再是他们的重量了:

 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在处理集合时应该是你的面包和黄油方法 – 它实际上是强大的,因为它适用于承诺数组的任何承诺,这些承诺映射到进一步承诺直接值之间的任何混合。