As someone who is diving into functional programming and just beginning to explore fp-ts, I am grappling with understanding the util functions provided. My current challenge involves figuring out how to handle TaskEither
s as fallbacks within an array.
I have a function that retrieves data for a specific id
, returning either an Error
or a Success
:
declare function getData(id: number): TaskEither<Error, Success>
My goal is to create a function that loops through an array of id
s (e.g. [1, 2, 3, 4]
), fetching data for each one. It should stop at the first successful TaskEither
and return Right<Success>
. If all TaskEither
s fail, it should aggregate their errors into a Left<Error[]>
.
import { map } from 'fp-ts/lib/Array';
const program: TaskEither<Error[], Success>
= pipe(
[1, 2, 3, 4],
map(getData),
/*
* Now I have a TaskEither<Error, Success>[]
* What comes next?
*/
);
I attempted a similar approach, but encountered some clear issues (outlined below):
import { map, sequence } from 'fp-ts/lib/Array';
import { map as mapTaskEither } from 'fp-ts/lib/TaskEither'
const program: TaskEither<Error, Success>
= pipe(
[1, 2, 3, 4],
map(getData),
sequence(taskEither), // This now results in a TaskEither<Error, Success[]>
mapTaskEither(successes => successes[0])
);
Challenges with this method:
- It executes
getData
for all IDs without stopping at the first success - If any of the
getData
calls encounter an error, the overallprogram
will error out, even if previous calls were successful - The errors are not accumulated into an array of
Error[]