首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fp-ts如何处理具有不同权限类型的多个

fp-ts如何处理具有不同权限类型的多个
EN

Stack Overflow用户
提问于 2021-10-05 21:31:13
回答 1查看 89关注 0票数 1

Promises的右侧不能很好地对齐时,处理Eithers的Eithers的最佳方法是什么?在这个场景中,我有三个非依赖的“先决条件”操作,表示为Eithers (具有不同的右手类型)。如果它们都成功了,我就不会继续第四个操作了。如果三个操作中的任何一个失败,我都不想继续执行第四个操作。

在这一点上,我有一个解决方案编译,但对可读性不满意。在这种情况下,肯定有更好的方法来处理多个Either

代码语言:javascript
复制
    //promise of Either<ApiError, CustomerDTO>
    const customer = this.customerService.createCustomer(siteOrigin, createCustReq);

    //promise of Either<ApiError, LocationDTO>
    const location = this.locationService.getRetailOnlineLocation(siteOrigin);

    //promise of Either<ApiError, StationDTO>
    const station = this.stationService.getRetailOnlineStation(siteOrigin);
    
    //execute previous concurrently
    const locationAndStationAndCustomer = await Promise.all([location, station, customer]);

    const locationE = locationAndStationAndCustomer[0];
    const stationE = locationAndStationAndCustomer[1];
    const customerE = locationAndStationAndCustomer[2];


    //How to make this better?
    const stationAndLocationAndCustomer = E.fold(
      (apiErr: ApiError) => E.left(apiErr),
      (location: LocationDTO) => {
        return E.fold(
          (apiErr: ApiError) => E.left(apiErr),
          (station: StationDTO) =>
            E.right(
              E.fold(
                (err: ApiError) => E.left(err),
                (customer: CustomerDTO) =>
                  E.right({ location, station, customer })
              )(customerE)
            )
        )(stationE);
      }
    )(locationE);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-10 07:25:25

我认为这些评论越来越接近正确的答案。sequenceT是解决这类问题的正确方法。

代码语言:javascript
复制
import { sequenceT } from 'fp-ts/Apply'
import * as E from 'fp-ts/Either';

const seq = sequenceT(E.Apply);

return pipe(
  await Promise.all([location, station, customer]),
  seq, // [Either<...>, Either<...>, Either<...>] => Either<ApiError, [...]>
  // map is a bit less cumbersome. If the value was Left it returns Left
  // otherwise it calls the function which returns a new Right value from
  // what the function returns
  E.map(([loc, sta, cust]) => ({
    location: loc,
    station: sta,
    customer: cust,
  })), 
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69457481

复制
相关文章

相似问题

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