我目前正在学习如何在Node.js中使用Promise。
因此,我的第一个挑战是列出目录中的文件,然后使用异步函数获取每个文件的内容。我想出了以下解决方案,但我强烈感觉这不是最优雅的方式,特别是第一部分,即我将异步方法“转换”为Promise的部分。
// 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
}
现在将两个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)
})
就像我之前写的那样,它可以返回期望的结果,但我相信一定有更加优雅的方法。
Async
函数:readdirAsync
,readFileAsync
。 - Wtower