我正在试验js_of_ocaml
和node.js.如您所知,node.js大量使用回调来实现异步请求,而不引入显式线程。OCaml/Node.JS上的Lwt.async和Lwt_main.run之间有什么区别?
在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
由于没有结合Lwt_main
为node.js的,我不得不与Lwt.async
我的代码运行。运行代码与Lwt.async
而不是Lwt_main.run
有什么区别 - 后者在node.js中不存在?是否保证程序会在退出之前等待异步线程完成,或者这是我的代码中一个幸运但随机的行为?
我从来没有使用主运行我绑定的NodeJS,顶层单位罚款 –
@EdgarAroutiounian请纠正我,如果我错了:你写的绑定不使用LWT可言,对不对?您是否在使用这些绑定的代码中使用Lwt?也许你想在这里添加一些答案,以避免聊天。 :) –
我有话要说,但它不是一个真正的答案,有种评论和洞察力。 –