我有一个由2个嵌套请求组成的流,其中可能有3个不同的结果:
这两个请求都可能引发错误,因为这实现了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)第一个请求返回用户授权的布尔状态。第二,如果用户是经授权的,请求将加载用户配置文件。
作为回报,我希望获得下一个签名、错误或匿名/配置文件:
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状态。
如何解决这个问题?
发布于 2020-05-03 05:41:20
不知道您是否过度简化了实际代码,但是E.Either<true, false>与boolean是同构的,所以让我们继续使用更简单的东西。
declare const isAuth: () => TE.TaskEither<Error, boolean>;
declare const getProfile: () => TE.TaskEither<Error, Profile>;然后根据其是否已创建添加条件分支,并包装getProfile的结果:
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作为命名函数来获得正确的类型,如下所示:
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)
);https://stackoverflow.com/questions/61559808
复制相似问题