In the library fp-ts
, promises are represented by either Task
or TaskEither
monads, both of which deal with asynchronous computations. The TaskEither
monad adds a failure modeling feature and is essentially similar to Task<Either<...>>
.
To compose Kleisli Arrows, you can use the chain
operation for monads and flow
(pipe operator), which resembles the application of the >=>
operator in Haskell.
Let's demonstrate with an example using
TaskEither
:
const f = (a: A): Promise<B> => Promise.resolve(42);
const g = (b: B): Promise<C> => Promise.resolve(true);
To convert functions that return
Promise
into ones returning
TaskEither
, you can utilize
tryCatchK
1:
import * as TE from "fp-ts/lib/TaskEither";
const fK = TE.tryCatchK(f, identity); // (a: A) => TE.TaskEither<unknown, B>
const gK = TE.tryCatchK(g, identity); // (b: B) => TE.TaskEither<unknown, C>
Compose them together:
const piped = flow(fK, TE.chain(gK)); // (a: A) => TE.TaskEither<unknown, C>
If you are interested, here is a block of code that can be copied and pasted into Codesandbox:
// you could also write:
// import { taskEither as TE } from "fp-ts";
import * as TE from "fp-ts/lib/TaskEither";
// you could also write:
// import {pipeable as P} from "fp-ts"; P.pipe(...)
import { flow, identity, pipe } from "fp-ts/lib/function";
import * as T from "fp-ts/lib/Task";
type A = "A";
type B = "B";
type C = "C";
const f = (a: A): Promise<B> => Promise.resolve("B");
const g = (b: B): Promise<C> => Promise.resolve("C");
// Alternative to `identity`: use `toError` in fp-ts/lib/Either
const fK = TE.tryCatchK(f, identity);
const gK = TE.tryCatchK(g, identity);
const piped = flow(fK, TE.chain(gK));
const effect = pipe(
"A",
piped,
TE.fold(
(err) =>
T.fromIO(() => {
console.log(err);
}),
(c) =>
T.fromIO(() => {
console.log(c);
})
)
);
effect();
Why avoid promises?
JavaScript Promises do not conform to a monadic API; they are eagerly computed 2. In functional programming, side effects should be delayed as much as possible, requiring a compatible wrapper like Task
or TaskEither
.
1 The function identity
simply forwards the error in case of failure. You could also consider using toError
.
2 For historical insights, reading Incorporate monads and category theory #94 might be worthwhile.