r/functionalprogramming • • Jun 07 '26

Question converting imperative JS fetching into functional style

hello , im a programmer that likes to dabble into webdev from time to time .. recently i got into functional programming (haskell , scala , etc) and i realized that using fetch() in javascript returns a Promise<> which has methods like .then() and .catch() that kinda makes it act like a monad . heres a snippet from the mdn

function fetchCurrentData() {
  return fetch("current-data.json").then((response) => {
    if (response.headers.get("content-type") !== "application/json") {
      throw new TypeError();
    }
    const j = response.json();
    return j;
  });
}

now i wonder if my code that is written imperatively can be converted into this style , and how would error handling work ? should i use async ? can someone help guide me thru this ?

public async callApi(path: string) {
    try {
        const res = await fetch(this.url + path);
        if (!res.ok)
            throw new Error(`status: ${res.status}`);

        const json = await res.json();
        return json;
    } catch (error: any) {
        console.error(error.message);
    }
}
7 Upvotes

13 comments sorted by

View all comments

Show parent comment

3

u/rinn7e Jun 11 '26

Actually, you can make it even cleaner, something like this:

...
export const checkStatus = (res: Response): E.Either<Error, Response> =>
  res.ok 
    ? E.right(res) 
    : E.left(new Error(`status: ${res.status}`));


export const callApi = (
  baseUrl: string,
  path: string
): TE.TaskEither<Error, any> =>
  pipe(
    safeFetch(baseUrl + path),
    TE.chainEitherK(checkStatus),
    TE.chain(safeJson)
  );