将承诺与 setTimeout 结合使用

Using promises with setTimeout

我是 Reason 的新手,目前正在尝试将个人项目从 js 转换为 reason。到目前为止,除了异步内容之外,大多数情况下它都很容易。 我无法延迟地递归调用我的函数。 我有一个函数 getPrice,其中 returns 是 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 应该是类型单位

不幸的是,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
         )
       }
   )
);