【发布时间】:2019-05-21 16:29:46
【问题描述】:
我从这个SO question 获得了很多关于抓取目录和搜索文件的帮助。我正在尝试使我的readPackageFiles 函数使用给我的Parallel 函数;但是,我正在努力让它发挥作用。
错误:
UnhandledPromiseRejectionWarning: TypeError: Cannot use 'in' operator to search for 'throws' in 1
at readFile (/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/jsonfile/index.js:22:16)
at Promise (/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/universalify/index.js:13:12)
at new Promise (<anonymous>)
at readFile (/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/universalify/index.js:7:14)
at Array.map (<anonymous>)
at /Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/dist/index.js:1:1833
at <anonymous>
(node:70097) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 63)
(node:70097) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/jsonfile/index.js:43
callback(null, obj)
问题:如何使 readPackageFiles 与 Parallel 配合使用?
import {readdir, stat, readJson} from 'fs-extra';
import {join, basename} from 'path';
const Parallel = p =>
({
map: async f =>
Promise.all((await p).map(f))
,
filter: async f =>
Promise.all((await p).filter(f))
,
flatMap: async f =>
Promise.all((await p).map(f)).then(ys => [].concat(...ys))
,
});
const files = async (path = '.') =>
(await stat(path)).isDirectory()
? Parallel(readdir(path))
.flatMap(f => files(join(path, f)))
: [path];
const search = async (query, path = ".") =>
Parallel (files (path))
.filter (f => basename (f) === query);
// How can I write this to use Parallel
const readPackageFiles = async (packages) => await Promise.all(packages.map(async x => (await readJson(x))));
// this will not work but it's my attempt
const readPackageFilesNOTWORKING = async(path = ".") =>
Parallel (search('package.json', path))
.map (readJson)
用法:
search('package.json', '.')
.then(readPackageFiles)
.then(console.log);
【问题讨论】:
标签: javascript function asynchronous functional-programming refactoring