javascript - 分析通过路径列表的函数

标签 javascript asynchronous es6-promise

我需要一个异步“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/

相关文章:

javascript - 需要使用具有连接和端点的 jsplumb 验证页面

javascript - 获取数组中出现次数最多的项

android - 如何使用一个异步任务从 android 更新两个不同的 Mysql 表?

JavaScript Promise 封装在函数中还是裸露的?

javascript - 获取被单击元素在 HTML 源代码中的插入符号 [开始、结束] 位置

javascript - JS - 防止 "crash"浏览器实现中的长循环 javascript

javascript - 异步Servlet客户端、服务器推送

javascript - Node.js - Promise 执行顺序问题

javascript - React/Redux 应用程序中 js Promise 中 Uncaught Error

javascript - Promise.resolve 内部引用混淆