在Scala.js中轮询未来



我有一个跨平台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(中执行处理,但即使知道这不是一种合适的方式,Future结果是否可以在Scala.js中以某种方式轮询?

使用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))

在这里摆弄

最新更新