首页 > 解决方案 > (已解决)如何在 FP-TS 中链接依赖的 TaskEither 操作

问题描述

我是 FP-TS 的新手,但仍然不太了解如何使用TaskEither. 我正在尝试异步读取文件,然后使用 yaml-parse-promise 解析生成的字符串。

==编辑==

我用文件的全部内容更新了代码以提供更多上下文,并应用了 MnZrK 提供的一些建议。抱歉,我还是 FP-TS 的新手,我仍在努力让类型匹配。

现在我的错误在于该map(printConfig)行:

Argument of type '<E>(fa: TaskEither<E, AppConfig>) => TaskEither<E, AppConfig>' is not assignable to parameter of type '(a: TaskEither<unknown, AppConfig>) => Either<unknown, Task<any>>'.
  Type 'TaskEither<unknown, AppConfig>' is not assignable to type 'Either<unknown, Task<any>>'.
    Type 'TaskEither<unknown, AppConfig>' is missing the following properties from type 'Right<Task<any>>': _tag, rightts(2345)

[我通过使用来自 TaskEither 而不是来自 Either 库的 getOrElse 解决了这个问题]

==结束编辑==

我已经使用 IOEither 成功地执行了此操作,作为与该项目的同步操作:https ://github.com/anotherhale/fp-ts_sync-example 。

我还在这里查看了示例代码: https ://gcanti.github.io/fp-ts/recipes/async.html

完整代码在这里:https ://github.com/anotherhale/fp-ts_async-example

import { pipe } from 'fp-ts/lib/pipeable'
import { TaskEither, tryCatch, chain, map, getOrElse } from "fp-ts/lib/TaskEither";
import * as T from 'fp-ts/lib/Task';
import { promises as fsPromises } from 'fs';
const yamlPromise = require('js-yaml-promise');

// const path = require('path');
export interface AppConfig {
  service: {
    interface: string
    port: number
  };
}

function readFileAsyncAsTaskEither(path: string): TaskEither<unknown, string> {
  return tryCatch(() => fsPromises.readFile(path, 'utf8'), e => e)
}

function readYamlAsTaskEither(content: string): TaskEither<unknown, AppConfig> {
  return tryCatch(() => yamlPromise.safeLoad(content), e => e)
}

// function getConf(filePath:string){
//   return pipe(
//       readFileAsyncAsTaskEither(filePath)()).then(
//           file=>pipe(file,foldE(
//               e=>left(e),
//               r=>right(readYamlAsTaskEither(r)().then(yaml=>
//                   pipe(yaml,foldE(
//                       e=>left(e),
//                       c=>right(c)
//                   ))
//               ).catch(e=>left(e)))
//           ))
//       ).catch(e=>left(e))
// }

function getConf(filePath: string): TaskEither<unknown, AppConfig> {
  return pipe(
    readFileAsyncAsTaskEither(filePath),
    chain(readYamlAsTaskEither)
  )
}

function printConfig(config: AppConfig): AppConfig {
  console.log("AppConfig is: ", config);
  return config;
}

async function main(filePath: string): Promise<void> {
  const program: T.Task<void> = pipe(
    getConf(filePath),
    map(printConfig),
    getOrElse(e => {
      return T.of(undefined);
    })
  );

  await program();
}

main('./app-config.yaml')

结果输出是: { _tag: 'Right', right: Promise { <pending> } }

但我想要生成的 AppConfig: { service: { interface: '127.0.0.1', port: 9090 } }

标签: fp-ts

解决方案


所有这些都是不必要的e=>left(e).catch(e=>left(e))您的第二种方法更惯用。

// convert nodejs-callback-style function to function returning TaskEither
const readFile = taskify(fs.readFile);
// I don't think there is `taskify` alternative for Promise-returning functions but you can write it yourself quite easily
const readYamlAsTaskEither = r => tryCatch(() => readYaml(r), e => e);

function getConf(filePath: string): TaskEither<unknown, AppConfig> {
  return pipe(
    readFile(path.resolve(filePath)),
    chain(readYamlAsTaskEither)
  );
}

现在你的getConf回报TaskEither<unknown, AppConfig>实际上是一个() => Promise<Either<unknown, AppConfig>>. 如果您有比 更具体的错误类型unknown,请改用它。

为了“解包”实际值,您需要有一些主入口点功能,您可以在其中使用mapchain(即将其打印到控制台)编写您需要对配置执行的其他内容,然后应用一些错误处理来摆脱Either部分,最后得到公正Task(实际上只是懒惰() => Promise):

import * as T from 'fp-ts/lib/Task';

function printConfig(config: AppConfig): AppConfig {
  console.log("AppConfig is", config);
  return config;
}

function doSomethingElseWithYourConfig(config: AppConfig): TaskEither<unknown, void> {
  // ...
}

async function main(filePath: string): Promise<void> {
  const program: T.Task<void> = pipe(
    getConf(filePath),
    map(printConfig),
    chain(doSomethingElseWithYourConfig),
    // getting rid of `Either` by using `getOrElse` or `fold`
    getOrElse(e => {
      // error handling (putting it to the console, sending to sentry.io, whatever is needed for you app)
      // ...
      return T.of(undefined);
    })
  );

  await program();
}

推荐阅读