RationalJS/future

map future, flatMap result

Closed this issue · 2 comments

I often find myself wanting a helper function with this signature:

(Future.t(Result.t('a, 'x)), ('a => Result.t('b, 'x))) => Future.t(Result.t('b, 'x))

It's easy enough to write this function myself, but I thought if there's enough demand for this pattern, maybe it makes sense to add a helper to the library.

Example usage: fetch remote data as JSON, then decode JSON

type data;
type error = NetworkError | ParseError;

let decode: Js.Json.t => Result.t(data, error);

let getData: string => Future.t(Result.t(Js.Json.t, error));

getData("url")
  |. Future.map(result => Result.flatMap(result, decode));

/* if this new function existed, with a terrible name... */
getData("url")
  |. Future.mapOkFlatMapInner(decode);

/* both of the above expressions would produce Future.t(Result.t(data, error)) */

Maybe this doesn't provide enough value to be useful... If you just alias Belt.Result's flatMap and flip the arguments:

let flatMap = (fn, r) => Belt.Result.flatMap(r, fn);
getData("url") -> Future.map(flatMap(decode));

This is already more clear than any name I can think of for a specialized version of this function. Feel free to close this, unless you think there's some value in Future providing a helper.

Per the thumbs-ups, it seems people agree, so I'm going to close this.