【发布时间】:2016-01-21 16:40:51
【问题描述】:
我正在尝试使用 js_of_ocaml 和 node.js。如您所知,node.js 大量使用回调来实现异步请求,而无需引入显式线程。
在 OCaml 中,我们有一个非常好的线程库 Lwt,它带有一个非常有用的语法扩展。我编写了一个绑定到某个节点库(AWS S3 客户端)的原型,并添加了一个 lwt-ish 层来隐藏回调。
open Lwt.Infix
open Printf
open Js
let require_module s =
Js.Unsafe.fun_call
(Js.Unsafe.js_expr "require")
[|Js.Unsafe.inject (Js.string s)|]
let _js_aws = require_module "aws-sdk"
let array_to_list a =
let ax = ref [] in
begin
for i = 0 to a##.length - 1 do
Optdef.iter (array_get a i) (fun x -> ax := x :: !ax)
done;
!ax
end
class type error = object
end
class type bucket = object
method _Name : js_string t readonly_prop
method _CreationDate : date t readonly_prop
end
class type listBucketsData = object
method _Buckets : (bucket t) js_array t readonly_prop
end
class type s3 = object
method listBuckets :
(error -> listBucketsData t -> unit) callback -> unit meth
end
let createClient : unit -> s3 t = fun () ->
let constr_s3 = _js_aws##.S3 in
new%js constr_s3 ()
module S3 : sig
type t
val create : unit -> t
val list_buckets : t -> (string * string) list Lwt.t
end = struct
type t = s3 Js.t
let create () =
createClient ()
let list_buckets client =
let cell_of_bucket_data data =
((to_string data##._Name),
(to_string data##._CreationDate##toString))
in
let mvar = Lwt_mvar.create_empty () in
let callback error buckets =
let p () =
if true then
Lwt_mvar.put mvar
(`Ok(List.map cell_of_bucket_data @@ array_to_list buckets##._Buckets))
else
Lwt_mvar.put mvar (`Error("Ups"))
in
Lwt.async p
in
begin
client##listBuckets (wrap_callback callback);
Lwt.bind
(Lwt_mvar.take mvar)
(function
| `Ok(whatever) -> Lwt.return whatever
| `Error(mesg) -> Lwt.fail_with mesg)
end
end
let () =
let s3 = S3.create() in
let dump lst =
Lwt_list.iter_s
(fun (name, creation_date) ->
printf "%32s\t%s\n" name creation_date;
Lwt.return_unit)
lst
in
let t () =
S3.list_buckets s3
>>= dump
in
begin
Lwt.async t
end
由于 node.js 没有绑定到 Lwt_main,因此我必须使用 Lwt.async 运行我的代码。使用Lwt.async 而不是使用Lwt_main.run 运行代码有什么区别——后者在node.js 中不存在?是否保证程序会等到异步线程完成后再退出,或者这是我的代码的一种相当幸运但随机的行为?
【问题讨论】:
-
我从来没有为我的 nodejs 绑定使用主运行,顶级单元就可以了
-
@EdgarAroutiounian 如果我错了请纠正我:您编写的绑定根本不使用 Lwt,对吧?您是否在使用这些绑定的代码中使用 Lwt?也许您想在此处的答案中添加更多详细信息,以避免聊天。 :)
-
我有话要说,但不是真正的答案,有点像 cmets 和洞察力。
标签: node.js ocaml js-of-ocaml ocaml-lwt