Skip to content

Instantly share code, notes, and snippets.

@lilactown
Created September 28, 2017 03:18
Show Gist options
  • Save lilactown/5b6359e4d6e8b35a237439a2f61aea04 to your computer and use it in GitHub Desktop.
Save lilactown/5b6359e4d6e8b35a237439a2f61aea04 to your computer and use it in GitHub Desktop.
Making it easier to keep our Promises
module type Promise = {
type t 'a;
let then_: ('a => t 'b) => t 'a => t 'b;
let resolve: 'a => t 'a;
let all: array (t 'a) => t (array 'a);
let race: array (t 'a) => t 'a;
let make: (resolve::('a => unit) [@bs] => reject::(exn => unit) [@bs] => unit) => t 'a;
};
module Make (P: Promise) => {
/**
* Creating promises
**/
let return = P.resolve;
let make = P.make;
/**
* Handling values
**/
let bind = P.then_;
let map fn => bind @@ (fun v => return (fn v));
/**
* Lists of promises
*/
let join plist => Array.of_list plist |> P.all |> map Array.to_list;
let race plist => P.race @@ Array.of_list plist;
/**
* Side effects
**/
let tap fn =>
bind (
fun v => {
fn v;
return v
}
);
let complete (fn: 'a => P.t unit) => ignore @@ bind @@ (fun v => fn v);
let async (fn: unit => P.t 'a) => ignore @@ fn ();
/**
* Error handling
*/
/* TBD*/
module Infix = {
let (>>=) p fn => bind fn p;
let (=<<) = bind;
let (>|=) p fn => map fn p;
let (=|<) = map;
let (<?>) p p' => race [p, p'];
let (<&>) p p' => join [p, p'];
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment