r/functionalprogramming • u/Mindless_Ad_9792 • 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
4
u/780Chris Jun 08 '26 edited Jun 08 '26
The top snippet is the old way of dealing with promises (promise chaining) and your snippet is the new, preferred way of dealing with promises. The point is to make asynchronous code look synchronous.
If you really want to use promise chaining you handle errors by adding a ‘.catch()’ to the chain. If an error is thrown in a ‘.then()’ it seeks the next ‘.catch()’ handler. You would then rethrow the error so it can be handled by the caller of ‘callApi’.
Again though, this is no longer the preferred way of doing things in JS.
6
u/ic6man Jun 07 '26
My first suggestion would be to not swallow the error. Yikes.
Also. Minor nit but no need to await the json if you are just going to return it. Just return the promise.
6
u/mister_drgn Jun 07 '26
Doesn’t every functional language try to to be relevant by transpiling to JavaScript anyway? If you want to explore functional programming in web dev, why not learn Purescript or something.
9
u/tpawap Jun 07 '26
Your two snippets are exactly the same "level of imperativeness", aren't they? I don't see a difference.
What you could do:
4
u/DecadentCheeseFest Jun 08 '26
OP, this is quite broad, but for this topic I think it’s beneficial to read about what Scott Wlaschin calls Railway Oriented Programming. His guide is useful and very readable even though it’s in F#.
The ‘ergonomics’ of TypeScript simply don’t map well to what we expect to have when we do functional programming - errors as values, proper enum types, exhaustive pattern-matching, a functional utility belt - and even the best libraries which fill this gap (Effect-TS) are quite awkward to use.
That said, Scott’s writing can help you understand what’s missing and achieve an approximation of functional programming principles and approaches.
4
u/ImYoric Jun 08 '26
Yes, and it's not an accident 😄
Note that
async/awaitwas also designed as a monad with syntactic sugar (it was more explicit in the early drafts, when it was calledTask.spawn, iirc), but yeah you can remove the sugar if you wish.7
u/recursion_is_love Jun 07 '26
promise is technically not a monad
https://rybicki.io/blog/2023/12/23/promises-arent-monads.html
3
u/rinn7e Jun 11 '26 edited Jun 11 '26
You can use fp-ts library: https://gcanti.github.io/fp-ts/
The result would be something like this
pipe(a, func1, func2)is equivalent to haskella & func1 & func2>>=There're also:
3
u/[deleted] Jun 07 '26
[removed] — view removed comment