我需要一个异步“getTypes”函数来分析传递的路径列表并返回一个描述每个路径中内容的数组。功能在任何情况下都应该运行良好。如果异步操作期间发生错误,则该路径的值为“null”。我尝试编写一个函数,但它不起作用。
const getTypes = (arr) => {
const prom = arr.reduce((acc, path) => (
acc.then((data) => {
return fs.stat(path).isFile() ? 'file' : 'directory';
})
.catch(() => null)
), Promise.resolve());
return prom;
}
它应该如何工作:
getTypes(['/etc', '/etc/hosts', '/undefined']).then(console.log);
// ['directory', 'file', null]
不知道怎么办,有谁可以帮忙吗?拜托了
最佳答案
方法 1
async function getTypes(arr) { // Mark the function as async
return Promise.all(arr.map(async (path) => { // Promise.all will wait for all mapped calls to be resolved
try {
const stat = await fs.stat(path) // fs.stat is async
} catch(e) {
return null
}
return stat.isFile() ? 'file' : 'directory';
}));
}
方法2:(修改OP代码)
const getTypes = arr => {
const prom = arr.reduce((acc, path) => {
acc
.then(data => {
return Promise.all([fs.stat(path), Promise.resolve(data)]);
})
.then(([stat, data]) =>
stat.isFile()
? [Promise.resolve(data.push("file")), false]
: [Promise.resolve(data.push("directory")), false]
)
.catch(() => Promise.resolve([data, true])) // so the next `then` can have access to data
.then([data, failed] => failed === true ? Promise.resolve(data.push(null)) : Promsie.resolve(data)
}, Promise.resolve([]));
return prom;
};
方法 3:(不具有容错能力。即,如果在任何异步调用中抛出错误,Promise.all 都会失败):
function getTypes(arr) {
const deferreds = arr.map(fs.stat);
return Promise.all(deferreds).then(stats =>
stats.map(stat => (stat.isFile() ? "file" : "directory"))
);
}
方法 4:(稍微修改 #3 以使其具有容错能力)
const getFileType = stat => stat.isFile() ? 'file' : 'directory'
const getFileStat = path => fs.stat(path).then(getFileType).catch(() => null)
const getTypes = paths => Promise.all(paths.map(getFileStat))
关于javascript - 分析通过路径列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60587370/