【问题标题】:How to dispatch one argument to multiple function in fp-ts如何在 fp-ts 中将一个参数分派给多个函数
【发布时间】:2021-08-07 12:39:37
【问题描述】:

我有以下代码

export const getPostData = (id: string) =>
  pipe(
    getFullPathFileNameForPosts(`${id}.md`), // IO<string>
    chain(getFileContents), // IO<string>
    chain(getMatter), // IO<matter.GrayMatterFile<string>>
    map(R.pick(['data'])),
    bind('id', () => () => id)
  );

以上函数getPostData()retun

IO<{
  data: {[key: string]: any};
  id: string;
}>

现在我必须在返回的结果中添加一些文件,比如说content,结果看起来像

IO<{
  data: {[key: string]: any};
  id: string;
  content: string;
}>

我写了一个新函数getContent = (matter: matter.GrayMatterFile&lt;string&gt;) =&gt; {...},现在如何将这个函数添加到组合函数getPostData中?

我想问的主要问题是如何将值分成不同的函数在组合函数中进行处理。

因为chain(getFileContents)中的getFileContents函数需要读取文件,所以我不想读取这个文件两次

【问题讨论】:

    标签: typescript fp-ts


    【解决方案1】:

    您可以继续使用bindbindTo 来保留您需要的所有值,直到您完成使用它们为止。

    由于您需要 matter.GrayMatterFile 作为 getContent 函数的输入,因此您需要将该值“保留”一段时间。

    这是一种可能的方法:

    import { pipe} from 'fp-ts/lib/function'
    import { chain, map, bind, bindTo, IO, of } from 'fp-ts/lib/IO'
    import { GrayMatterFile } from 'gray-matter'
    
    declare const getMatter: (fileContents: string) => IO<GrayMatterFile<string>>
    
    declare const getFileContents: (filepath: string) => IO<string>
    
    declare const getFullPathFileNameForPosts: (filename: string) => IO<string>
    
    declare const getContent: (file: GrayMatterFile<string>) => IO<string>
    
    export const getPostData = (id: string) =>
      pipe(
        getFullPathFileNameForPosts(`${id}.md`), // IO<string>
        chain(getFileContents), // IO<string>
        chain(getMatter), // IO<matter.GrayMatterFile<string>>
        bindTo('grayMatterFile'),
        bind('content', ({ grayMatterFile }) => getContent(grayMatterFile)),
        map(({ content, grayMatterFile }) => ({
          content: content,
          data: grayMatterFile.data,
          id
        })),
      );
    

    【讨论】:

    • 感谢您对我的大力帮助!
    • 也可以使用sequenceT(reader) 并将您发送的参数视为读者的上下文。 pipe(getArg(), sequenceT(reader)(fnThatTakesArg, fn2ThatTakesArg, fn3ThatTakesArg), ([res1, res2, res3]) =&gt; ...
    猜你喜欢
    • 2023-02-01
    • 2023-01-26
    • 2012-08-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多