javascript - 如何在 node.js 中为 Promise 运行 for 循环
问题描述
我有一个返回承诺的函数。Promise 实际上读取一个 JSON 文件并将该文件的一些数据推送到一个数组中并返回该数组。我可以使用单个文件来执行此操作,但我想运行具有多个文件路径的 for 循环,并希望将每个 Promise 的所有结果(解析)推送到一个数组中。正确的做法是什么?
在以下代码中,directoryName 是一个承诺的结果。这基本上是一个目录名称数组。在 secondMethod 函数中,我仅使用数组中的第一个目录名称来操作该目录中的文件。假设数组中的每个目录都有 t.json 文件。
let secondMethod = function(directoryName) {
let promise = new Promise(function(resolve, reject) {
let tJsonPath = path.join(directoryPath, directoryName[0], 't.json')
jsonfile.readFile(tJsonPath, function(err, obj) {
let infoRow = []
infoRow.push(obj.name, obj.description, obj.license);
resolve(infoRow)
})
}
);
return promise;
}
如何在 directoryName 数组上运行循环,以便为数组的每个元素执行 jsonfile.readFile 并将其结果存储在全局数组中?
解决方案
您需要使用Promise.all
将每个名称映射到Promise
. 还要确保检查reject
以防出现错误:
const secondMethod = function(directoryName) {
return Promise.all(
directoryName.map((oneName) => new Promise((resolve, reject) => {
const tJsonPath = path.join(directoryPath, oneName, 't.json')
jsonfile.readFile(tJsonPath, function(err, obj) {
if (err) return reject(err);
const { name, description, license } = obj;
resolve({ name, description, license });
})
}))
);
};
// Invoke with:
secondMethod(arrOfNames)
.then((results) => {
/* results will be in the form of
[
{ name: ..., description: ..., license: ... },
{ name: ..., description: ..., license: ... },
...
]
*/
})
.catch((err) => {
// handle errors
});
推荐阅读
- matplotlib - 如何在 PyQt5 中滚动浏览 numpy 数组图像?
- angular - 运行 angular 2 app npm start 时出错
- c++11 - 如何让 wxButton 自行销毁?
- assembly - 乘法后如何除以2个输入?
- android - 如何将两个字符串解析为一个文本视图
- vba - 避免代码重复
- oracle - TNS 侦听器当前不知道连接描述符中给出的 SID
- extent - 范围报告:Klov:查看测试用例历史/搜索时,如何限制其他项目中测试用例的可见性
- javascript - HTML,Javascript:将新元素附加到当前空元素
- php - 如何通过添加两个值来添加重复值数组