1

我是 Reason 的新手,目前正在尝试将个人项目从 js 转换为 Reason。到目前为止,除了异步的东西之外,它一直很容易。我无法延迟递归地调用我的函数。我有一个getPrice返回 int 承诺的函数

type getPrice = unit => Js.Promise.t(int)

我想做另一个功能checkPrice,除非满足条件,否则它会无休止地通过给定的用户价格检查当前价格。

let rec checkPrice = (userPrice) =>
  Js.Promise.(
   getPrice()
    |> then_(
     (currentPrice) =>
       if (currentPrice >= userPrice) {
         resolve(currentPrice)
       } else {
         /* call this function with setTimeout */
         checkPrice(userPrice)
       }
   )
);

但我得到类型不匹配说setTimeout应该是单元类型

4

1 回答 1

-1

不幸的Js.Promise是,API 非常糟糕,主要是因为 JS API 完全不健全,但在 Reason 方面也没有经过深思熟虑。可能会有一些方便的修复Js.Promise,但希望在不久的将来,整个事情都会被适当的解决方案所取代。

但是,此时此地,您必须执行以下操作:

external toExn : Js.Promise.error => exn = "%identity";

let rec checkPrice = (userPrice) =>
  Js.Promise.(
    getPrice()
    |> then_(
     (currentPrice) =>
       if (currentPrice >= userPrice) {
         resolve(currentPrice)
       } else {
         Js.Promise.make((~resolve, ~reject) =>
           Js.Global.setTimeout(
             fun () =>
               checkPrice(userPrice)
               |> then_((v) => [@bs] resolve(v) |> Js.Promise.resolve)
               |> catch((e) => [@bs] reject(toExn(e)) |> Js.Promise.resolve)
               |> ignore,
             0
           ) |> ignore
         )
       }
   )
);
于 2017-11-07T08:53:48.870 回答