【问题标题】:Poll a Future in Scala.js在 Scala.js 中轮询未来
【发布时间】:2019-05-15 20:04:50
【问题描述】:

我在跨平台 JVM / JS 应用程序中拥有未来。未来在 JVM 中以如下方式轮询:

val load = Future(loadSometing())

if (load.isCompleted) {
  val loaded = Await.result(load, Duration.Inf)
  // now process it
}

这不适用于 Scala.js,因为 Scala.js 没有实现 Await。但是在我的情况下,我没有使用 Await 等待,只是为了得到我知道的结果已经存在。我知道一个正确的解决方案是使代码完全异步并在Future 处理程序(map 或 onComplete)中执行处理,但即使知道这不是正确的方法,也可以在 Scala 中以某种方式轮询Future 结果。 js?

【问题讨论】:

    标签: scala asynchronous future scala.js


    【解决方案1】:

    使用Future.value 轮询Future,无需等待/阻塞:

    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits.global
    
    val f = Future { 42 }
    println(f.value)
    
    js.timers.setTimeout(500) {
      println(f.value)
    }
    

    将打印

    None
    Some(Success(42))
    

    Fiddle here

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 2017-06-08
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多