Exploring the concept of kleisli composition in TypeScript by combining Promise monad with functional programming techniques using fp-ts

Is there a way to combine two kleisli arrows (functions) f: A -> Promise B and g: B -> Promise C into h: A -> Promise C using the library fp-ts?

Having experience with Haskell, I would formulate it as: How can I achieve the equivalent of the >=> (fish operator)?

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to get my React Typescript styled component slider to function within the component

Check out my demo here I created a simple react application using TypeScript and styled components. The main feature is a slider that adjusts the height of a red box. The red box is a styled component and I pass the height as a prop. Everything was fun ...

What is the best way to inform TypeScript when my Type has been altered or narrowed down?

In my application, I have a class that contains the API code: export class Api { ... static requestData = async ( abortController: React.MutableRefObject<AbortController | null> ) => { // If previous request exists, cancel it if ...

GraphQL query result does not contain the specified property

Utilizing a GraphQL query in my React component to fetch data looks like this: const { data, error, loading } = useGetEmployeeQuery({ variables: { id: "a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa" } }); When attempting to destructure the data, an error ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

Definition for TypeScript for an individual JavaScript document

I am currently attempting to integrate an Ionic2 app within a Movilizer HTML5 view. To facilitate communication between the Movilizer container client and the Ionic2 app, it is crucial to incorporate a plugins/Movilizer.js file. The functionality of this f ...

New approach in Typescript: Enhancement of child class with additional Event Listener overloads

One of my classes is structured like this: interface A extends EventEmitter{ on(event: "eventA", listener: () => void): this; } There is another class defined as follows: interface B extends A{ on(event: "eventB", listener: ...

How can we leverage RxJS combineLatest for observable filtering?

I'm exploring the possibility of utilizing combineLatest in an Angular service to eliminate the need for the activeFiler$ switch block (The service should achieve the same functionality). Currently, this is the structure of the component design (stack ...

Errors TS2585 and TS2304 encountered during compilation of TypeScript file using Axios

What steps should I take to fix the errors that arise when attempting to compile my TypeScript code using tsc index.ts? node_modules/axios/index.d.ts:75:3 - error TS1165: In an ambient context, a computed property name must reference an expression of lite ...

Arrange the columns in Angular Material Table in various directions

Is there a way to sort all columns in an Angular material table by descending order, while keeping the active column sorted in ascending order? I have been trying to achieve this using the code below: @ViewChild(MatSort) sort: MatSort; <table matSort ...

How can we prevent new chips (primeng) from being added, but still allow them to be deleted in Angular 2?

Hey there! I'm currently exploring how to make the chips input non-editable. I am fetching data objects from one component and using the keys of those objects as labels for the chips. Check out my HTML code below: <div class="inputDiv" *ngFor="le ...

Learn the technique for dynamically modifying Angular components within the main root component during runtime

I am looking to incorporate a dynamic form where the configuration button triggers the switch from app-login-form to login-config-form. app.component.html <div class="container p-5"> <app-login-header></app-login-header> <div cla ...

Error message: Invariant Violation: Portal.render() being caused by semantic-ui-react Basic Modal

As part of enhancing an existing React component, I attempted to include a basic modal (link to documentation). Everything was working well without the modal, but once I added it in following the semantic-ui-react guidelines, I encountered a runtime error ...

What causes the NavBar to show and hide within a specific range?

Recently, I encountered a perplexing issue with my navbar. It functions correctly except for one strange behavior that has left me baffled. Why does the menu appear when I adjust the width to 631px, but disappear at 600px? And vice versa – why does it wo ...

Can the Rxjs library's Observables of() function be used to output multiple values?

I am inquiring about this because I came across in the Angular documentation that of(HEROES) returns an Observable which emits a single value - an array of mock heroes. If I cannot use of(), do you have any alternative suggestions for me? I am cur ...

Combine form data from a reactive form into a string using interpolation

Currently, I am working with an object that has a string property embedded within it. The string in this property contains interpolation elements. For my user interface, I have implemented a reactive form with an input field. My goal is to display the ent ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

The 'prop' property is not found within the 'IntrinsicAttributes & CustomComponentProps' type

I developed a custom module with an interface for props, extending props from a file called /types/SharedProps.d.ts. However, when I import this module into a sample project, the extended props are not included in the component. Below is how the module&apo ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...