Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

How to compose async results?

$
0
0

Hi folks! After migrating all of my fetches and indexdb calls to promise<result<'a, exn>> it has become really annoying to unwrap and pattern match a chain of calls. Is there a better way to do monadic composition?

Something like

let fetchCart = getId >=> fetchCartById

I wrote an AsyncResult module with a Kleisli composition function but it looks really ugly when you have more than 2 functions. (I guess I could make a composeK3, composeK4 but I’d rather not)

module AsyncResult = {
  type t<'a, 'e> = promise<result<'a, 'e>>
  
  let composeK = (
    f: 'a => t<'b, 'e>,
    g: 'b => t<'c, 'e> 
  ): ('a => t<'c, 'e>) => async a => {
    let result = await f(a)
    switch result {
    | Ok(b) => await g(b)
    | Error(e) => Error(e)
    }
  }
}

Also since it’s a Result wrapped in a Promise, there’s no clean way to do map and flatMap. So I added them to AsyncResult, but it doesn’t feel quite right. There has to be a better way to do this right?

Here’s the full AsyncResult module

For now I think I’m not going to use the kcomp and just stick to flatMapping the AsyncResults, but I’d love to know if there’s a better way.

Thanks :smiley:


Viewing all articles
Browse latest Browse all 2592

Trending Articles