ocamlsynchronousocaml-lwt

How to synchronously execute an Lwt thread


Is there any way to synchronously execute a thread made with Lwt library?

To be specific, I am trying to run a series of post requests to a server that compute some value and returns a result.

Based on answers provided to this question:

How do I make a simple GET request in OCaml?

I can make it with either low level approach (sockets) or using the Cohttp library. The low level approach has the advantage of being immediate and straightforward but I would rather stick to the Cohttp (no need for read/write loop etc.). Unfortunately I am completely new to the Lwt and based on: https://mirage.io/wiki/tutorial-lwt I understand that the only way to get result from a t to a is to run Lwt_main.run which is suppose to be invoked at top level which is not an option for me.

TL:DR

Is there any way get a result from:

Client.get (Uri.of_string "http://localhost:8080/res")

without calling Lwt_main.run or is calling Lwt_main.run for each request (deep inside a code) not so bad idea ?


Solution

  • You can call Lwt_main.run deep inside the program, provided the call is not nested inside an outer call to Lwt_main.run. It sounds like it won't be nested in your case, so you can call it where you make the request.