RationalJS / future

A Js.Promise alternative for ReasonML
213 stars 15 forks source link

futurify - Js.Promise interop #4

Closed scull7 closed 6 years ago

scull7 commented 6 years ago

Here is the function that I'm using for Js.Promise conversion:

  let futurify = (promise, exn) =>
    Future.make((callback) =>
      promise
      |> Js.Promise.then_(res =>
        Ok(res)
        |> callback
        |> ignore
        |> Js.Promise.resolve
      )
      |> Js.Promise.catch(error=>
        Js.String.make(error)
        |> exn
        |> (err => Error(err))
        |> callback
        |> ignore
        |> Js.Promise.resolve
      )
    );

Perhaps this may be useful?

gilbert commented 6 years ago

Yes, this is a great reference, thank you.

Do you have any ideas on how to differentiate between different errors? For example, imagine a postgres query potentially throwing a NoSuchColumn error or a NotUnique error. In normal JS one could write if err instanceof NotUnique). I'm wondering if that's possible to translate to reason (I haven't given much thought to it yet).

scull7 commented 6 years ago

The exn function parameter pushes this responsibility to the caller. They are free to implement whatever scheme they like

gilbert commented 6 years ago

That's true, and is probably the best way to do it 👍

scull7 commented 6 years ago

Shall I make a PR?

gilbert commented 6 years ago

Yes please :) Put it in a new file FutureJs.re and name it fromPromise. I'd like to keep JS-specific code in its own module, if that makes sense.

scull7 commented 6 years ago

I've added the FutureJs.fromPromise method and associated tests.