What is the best way to handle Promise
s of Either
s when the Right side of the Either
s do not align nicely? In this scenario, I have three non-dependent, "prerequisite" operations represented as Either
s (with different right hand types). If they all succeed, I wan't to proceed with the fourth operation. If any of the three fails, I do not wan't to proceed with the fourth operation.
At this point, I have a solution compiling, but am not happy with readability. Surely there is a more elegant way to handle the multiple Either
s in this type of scenario?
//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);