分析传递路径列表的函数

Function that analyzes the list of passed paths

我需要一个异步 "getTypes" 函数来分析传递的路径列表和 returns 一个描述每个路径中内容的数组。函数在任何情况下都应该运行良好。如果在异步操作期间发生错误,则此路径的值为 "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]

不知道该怎么做,谁能帮忙?请

方法一

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';
   }));
}

方法二:(修改 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))