Javascript 映射并返回已解析承诺数组的函数的名称?

Javascript 映射并返回已解析承诺数组的函数的名称?,javascript,function,functional-programming,abstraction,Javascript,Function,Functional Programming,Abstraction,也许这是一个愚蠢的问题,但我最近发现自己经常使用这种抽象: async function giveMeAName(cbAsync, initValue) { return await Promise.all( initValue.map(cbAsync), ); } 问题:这是其他人的共同任务吗?如果有,它有名字吗?如果没有,也许只是部分意识到,那么它会提醒你什么吗?否则,我可以删除这个问题 目前,我正在为这组指令使用此函数。下面的代码将获取路径的所有目录,并收集包含packa

也许这是一个愚蠢的问题,但我最近发现自己经常使用这种抽象:

async function giveMeAName(cbAsync, initValue) {
  return await Promise.all(
    initValue.map(cbAsync),
  );
}
问题:这是其他人的共同任务吗?如果有,它有名字吗?如果没有,也许只是部分意识到,那么它会提醒你什么吗?否则,我可以删除这个问题

目前,我正在为这组指令使用此函数。下面的代码将获取路径的所有目录,并收集包含package.json的所有目录:

const directories = (await getDirNamesByPath(rootPath));
const paths = await giveMeAName(addExistAdaptor, directories.map(joinPathWithName(rootPath)));
return await giveMeAName(collectJson, paths.filter(hasPath));

根据我在应用程序中的需要,我使用不同的名称。有时我会对特定用例使用类似的函数,并相应地命名它。但是我经常使用的最通用的名称是
resolveAll()

但我不认为它有任何(半)官方名称。因此,请以对您最有意义的方式命名它。

几天前您问我,我试图帮助您,但您从未回答:(

我已经回答了类似的问题,这些问题概括了这一模式-

const Parallel = p =>
  ( { map: async f =>
        Promise .all ((await p) .map (x => f (x)))
    , filter: async f =>
        Promise .all ((await p) .filter (x => f (x)))
    , flatMap: async f =>
        Promise .all ((await p) .map (x => f (x))) .then (ys => [] .concat (...ys))
    , // ...
    }
  )
您可以看到它以这种方式用于
文件
,它递归地列出目录及其子目录中所有文件的所有路径-

const { readdir, stat } =
  require ("fs") .promises

const { join } =
  require ("path")

const files = async (path = ".") =>
  (await stat (path)) .isDirectory ()
    ? Parallel (readdir (path))
        .flatMap (f => files (join (path, f)))
    : [ path ]
还有一个专门的搜索功能,
search
,它返回与查询匹配的所有路径-

const { basename } =
  require ("path")

const search = async (query, path = ".") =>
  Parallel (files (path))
    .filter (f => basename (f) === query)
readPackages
递归读取指定路径上的所有
package.json
文件-

const { readFile } =
  require ("fs") .promises

const readPackages = async (path = ".") =>
  Parallel (search ("package.json", path))
    .map (readFile)
    .then
      ( buffers =>
          buffers .map (b => JSON .parse (String (b)))
      )
最后,还有一个稍微复杂一点的例子,
dirs
,它的工作原理类似于
文件
,但只递归地列出目录。递归的级别可以由
深度
参数控制-

const dirs = async (path = ".", depth = Infinity) =>
  (await stat (path)) .isDirectory ()
    ? depth === -1
        ? []
        : Parallel (readdir (path))
            .flatMap (f => dirs (join (path, f), depth - 1))
            .then (results => [ path, ...results ])
    : []

要查看这些程序在没有并行模块的情况下的外观,请参阅上面链接的问答。

可能是
mapAll
awaitAll


Bluebird有一个简单调用的类似函数,它做的事情非常类似(它返回映射的承诺,而不是解析它).

顺便说一句,严格来说,这不是函数式的,因为FP是基于定律的,主要是数学定律。从这个角度来看,
Promise
是一种行为怪异的非法数据类型。你应该研究一下像
Task
这样的一元类型,它们处理异步计算。