【发布时间】:2020-08-16 23:10:29
【问题描述】:
我有 2 个嵌套请求流,其中可能是 3 个不同的结果:
- 其中一个请求返回错误
- 用户不是匿名的,返回个人资料
- 用户是匿名的,返回 false
两个请求都可能引发错误,因此实现了TaskEither
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)
第一个请求返回用户授权的布尔状态。第二个请求加载用户配置文件如果用户被授权。
作为回报,我想获得下一个签名,Error 或 Either with Anonymous/Profile:
E.Either<Error, E.Either<false, Profile>>
我试着这样做:
pipe(
isAuth()
TE.chain(item => pipe(
TE.fromEither(item),
TE.mapLeft(() => Error('Anonimous')),
TE.chain(getProfile)
))
)
但作为回报,我得到了E.Either<Error, Profile>,这不方便,因为我必须手动从Error 中提取Anonymous 状态。
如何解决这个问题?
【问题讨论】:
-
E.Either<true, false>没有多大意义,因为类型是Either<boolean, boolean>,所以无论如何您都无法获得Either<boolean, TypeOfProfile>。您丢失Either层的原因是您作为合成的第一步执行的从Either到Task的自然转换TE.fromEither(item)。 -
糟糕,刚刚注意到您的初始 Either 具有文字作为类型参数,因此是
Either<true, false>。不过问题还是一样。 -
@bob 是的,我使用自然转换使其工作,因为我找不到编写正确管道的方法,这将返回
E.Either<false, Profile>或Option<Profile>,这不是重点,在右侧部分,并将第二个请求中的错误放在左侧部分 - 这是我的问题。
标签: javascript typescript functional-programming fp-ts