首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >链式fp-ts TaskEither (右)

链式fp-ts TaskEither (右)
EN

Stack Overflow用户
提问于 2020-05-02 13:02:28
回答 1查看 2.8K关注 0票数 3

我有一个由2个嵌套请求组成的流,其中可能有3个不同的结果:

  1. 的请求返回错误之一
  2. 用户不是匿名的,返回配置文件
  3. 用户是匿名的,返回假

这两个请求都可能引发错误,因为这实现了TaskEither

代码语言:javascript
复制
const isAuth = ():TE.TaskEither<Error, E.Either<true, false>>  
   => TE.tryCatch(() => Promise(...), E.toError)
const getProfile = ():TE.TaskEither<Error, Profile>  
   => TE.tryCatch(() => Promise(...), E.toError)

第一个请求返回用户授权的布尔状态。第二,如果用户是经授权的,请求将加载用户配置文件

作为回报,我希望获得下一个签名、错误或匿名/配置文件:

代码语言:javascript
复制
E.Either<Error, E.Either<false, Profile>>

我试着这样做:

代码语言:javascript
复制
pipe(
    isAuth()
    TE.chain(item => pipe(
      TE.fromEither(item),
      TE.mapLeft(() => Error('Anonimous')),
      TE.chain(getProfile)
    ))
  )

但作为回报,我得到了E.Either<Error, Profile>,巫婆不方便,因为我必须从Error手中提取Anonymous状态。

如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-03 05:41:20

不知道您是否过度简化了实际代码,但是E.Either<true, false>boolean是同构的,所以让我们继续使用更简单的东西。

代码语言:javascript
复制
declare const isAuth: () => TE.TaskEither<Error, boolean>;
declare const getProfile: () => TE.TaskEither<Error, Profile>;

然后根据其是否已创建添加条件分支,并包装getProfile的结果:

代码语言:javascript
复制
pipe(
  isAuth(),
  TE.chain(authed => authed 
    ? pipe(getProfile(), TE.map(E.right)) // wrap the returned value of `getProfile` in `Either` inside the `TaskEither`
    : TE.right(E.left(false))
  )
)

此表达式具有TaskEither<Error, Either<false, Profile>>类型。您可能需要为其适当地添加一些类型注释,我自己还没有运行代码。

编辑:

您可能需要提取lambda作为命名函数来获得正确的类型,如下所示:

代码语言:javascript
复制
const tryGetProfile: (authed: boolean) => TE.TaskEither<Error, E.Either<false, Profile>> = authed
  ? pipe(getProfile(), TE.map(E.right))
  : TE.right(E.left(false));

const result: TE.TaskEither<Error, E.Either<false, Profile>> = pipe(
  isAuth(),
  TE.chain(tryGetProfile)
);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61559808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档