繁体   English   中英

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

[英](Resolved) How to chain dependent TaskEither operations in FP-TS

我是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 } }

所有这些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 (实际上只是lazy () => 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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM