小编cdi*_*las的帖子

如何避免 fp-ts 中的嵌套 Monad 或优雅地处理它们?

我有一系列代码需要执行以下步骤(伪代码):

  jobsRepository.findById // <-- this returns a TaskEither
  jobs.openJob // <-- jobs.openJob returns an Either
  jobsRepository.update // <-- this returns another TaskEither
  createJobOpenedEvent // simple function that returns an IJobOpenedEvent
                       // given an IOpenJob
Run Code Online (Sandbox Code Playgroud)

如果我将这些步骤映射/链接在一起,我最终会得到一种TaskEither<IError, Either<IError, TaskEither<IError, IOpenJob>>>显然有点尴尬的类型。

我当前将所有这些扁平化为简单TaskEither<IError, IJobOpenedEvent>类型的解决方案如下所示(真实代码):

import { flatten } from "fp-ts/lib/Chain";
import { Either, either, left, right } from "fp-ts/lib/Either";
import {
  fromEither,
  TaskEither,
  taskEither,
  tryCatch,
} from "fp-ts/lib/TaskEither";

const createJobOpenedEvent = (openJob: jobs.IOpenJob): IJobOpenedEvent => ({
  name: "jobOpened",
  payload: openJob, …
Run Code Online (Sandbox Code Playgroud)

monads functional-programming typescript fp-ts

3
推荐指数
1
解决办法
1284
查看次数