我尝试在Scala.js中使用Promises和Futures。承诺是有效的,一旦涉及期货,我会得到警告和错误。
尝试:
val p1 = Promise[Int]
val f1: Future[Int] = p1.future
val p2 = Promise[Int]
val f2: Future[Int] = p2.future
val res1 = for {
v1 <- f1
v2 <- f2
} yield v1 + v2
val res2 = f1.flatMap(x => f2.map(y => x + y))
res1 onSuccess {
case x: Int => g.console.log(x);
}
res2 onSuccess {
case x: Int => g.console.log(x);
}
// callback in dom, using ScalaTags
// div(`class` := "btn btn-default", `type` := "button", onclick := click(1, p1))
def click(i: Int, p: Promise[Int])(x: dom.MouseEvent): Unit = {
g.console.log(i);
try {
p success i
}
catch {
case x: Throwable => println("again")
}
}
f1 onSuccess {
case x: Int => 1
}
然后我进入了快速行动:
[warn] Referring to non-existent class jl_Thread$UncaughtExceptionHandler
[warn] called from s_concurrent_impl_ExecutionContextImpl.init___ju_concurrent_Executor__F1
[warn] called from s_concurrent_impl_ExecutionContextImpl$.fromExecutor__ju_concurrent_Executor__F1__s_concurrent_impl_ExecutionContextImpl
[warn] called from s_concurrent_ExecutionContext$Implicits$.global$lzycompute__p1__s_concurrent_ExecutionContextExecutor
[warn] called from s_concurrent_ExecutionContext$Implicits$.global__s_concurrent_ExecutionContextExecutor
[warn] called from Lexample_H2$class.Lexample_H2$class__$init$__Lexample_H2__V
[warn]
我进入浏览器:
uncaught exception: java.lang.RuntimeException: System.getProperty() not implemented
缺少什么/未实现?我该如何实现它?有解决方法吗? 如何实现使用浏览器处理事件有意义的ExecutionContext?
答案 0 :(得分:31)
自Scala.js 0.6.0起,Scala的标准global
ExecutionContext
可用于Scala.js。您可以使用
import scala.concurrent.ExecutionContext.Implicits.global
// now you get to play with Futures
在Scala.js中,它是scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
的别名。此执行上下文将标准JavaScript事件循环中的作业排入队列。
请注意,任务是异步执行的,但不是并行执行的,因为JavaScript本身并不具有并行性的概念。如果需要并行性,则需要使用Web Workers,但这些并不提供Future
所需的共享内存模型。
适用于Scala.js的旧答案&lt; 0.6.0 强>
scala.scalajs.concurrent.JSExecutionContext
中有2个现有且有效的ExecutionContext
,内部对象Implicits
中有隐式版本。只需导入一个对你有意义的那个(可能queue
,另一个实际上不是异步)。
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
// now you get to play with Futures