你需要使用
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
});