当Promises的右侧不能很好地对齐时,处理Eithers的Eithers的最佳方法是什么?在这个场景中,我有三个非依赖的“先决条件”操作,表示为Eithers (具有不同的右手类型)。如果它们都成功了,我就不会继续第四个操作了。如果三个操作中的任何一个失败,我都不想继续执行第四个操作。
在这一点上,我有一个解决方案编译,但对可读性不满意。在这种情况下,肯定有更好的方法来处理多个Either?
//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);发布于 2021-10-10 07:25:25
我认为这些评论越来越接近正确的答案。sequenceT是解决这类问题的正确方法。
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,
})),
);https://stackoverflow.com/questions/69457481
复制相似问题