Eric Schaefer

Using Promise.all With ReasonML

This weekend I was wrestling with a clean way to resolve an array of promises using ReasonML, so I thought I would share a little reduced case in case it’s helpful to anyone.

let responses = [|1, 2|];

let fakeWait = number =>
  Js.Promise.make((~resolve, ~reject as _) => {
    ignore(Js.Global.setTimeout(() => resolve(. number), 2000));
    ();
  });

/* Expecting to see [1,2] logged after 2 seconds */

let _  = responses
  |> Array.map(fakeWait)
  |> Js.Promise.all
  |> Js.Promise.then_(res => res |> Js.log |> Js.Promise.resolve);

You can play with a live example that I created in the Reason repl. You can see the Javascript output that Bucklescript compiles down to as well, which is insightful for the pipe |> operator usage.