gpt4 book ai didi

javascript - 与 fs 和 bluebird 的 promise

转载 作者:IT老高 更新时间:2023-10-28 22:09:25 25 4
gpt4 key购买 nike

我目前正在学习如何在 nodejs 中使用 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)
})

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

最佳答案

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

事实上,由于这些功能不再发挥作用,因此您可以进一步调整它:

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 应该是你在使用集合时的基本方法 - 它真的很强大,因为它适用于任何事情,从一个 promise 到一系列 promise ,再到进一步 promise ,再到任何混合之间的直接值。

关于javascript - 与 fs 和 bluebird 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19429193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com