【问题标题】:Using promises with setTimeout使用带有 setTimeout 的 Promise
【发布时间】:2017-11-07 18:40:19
【问题描述】:

我是 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应该是单元类型

【问题讨论】:

标签: asynchronous promise reason bucklescript


【解决方案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
         )
       }
   )
);

【讨论】:

  • 啊,现在明白了,非常感谢您的解释是的,异步(承诺)是现在唯一值得畏缩的部分,休息是绝对的乐趣另外想知道,类型检查器是否可以强迫我为承诺 ?就像它提供非详尽的模式匹配一​​样?
  • 它可以,甚至还有一个包装承诺的库:github.com/wokalski/vow
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多