I have a pipe like this
const asyncFn = (x) => {
return Future.tryP(() => Promise.resolve(x + ' str2'))
};
const pipeResult = S.pipe([
x => S.Right(x + " str1"), // some validation function
S.map(asyncFn),
])("X");
pipeResult.fork(console.error, console.log);
I want to do some async operation in asyncFn
.
The problem is when I have Right
as input I can fork it anymore.
When I log the pipeResult
I see this:
Right (tryP(() => Promise.resolve(x + ' str2')))
How can I do this?
Either a b
andFuture a b
are both capable of expressing failure/success. When working with asynchronous computations it is usually better to useFuture a b
rather thanFuture a (Either b c)
. The simpler, flatter type requires less mapping:S.map (f)
rather thanS.map (S.map (f))
. Another advantage is that the error value is always in the same place, whereas withFuture a (Either b c)
botha
andb
represent failed computations.We may, though, already have a validation function that returns an either. For example:
If we have a value
fut
of typeFuture String String
, how do we validate the email addressfut
may contain? The first thing to try is alwaysS.map
:It would be nice to avoid this nesting. In order to do so, we first need to define a function from
Either a b
toFuture a b
:We can now transform an either-returning function into a future-returning function:
Let's revisit our use of
S.map
:We still have nesting, but now the inner and outer types are both
Future String _
. This means we can replaceS.map
withS.chain
to avoid introducing nesting: