Scala.js的期货

tod*_*d3a 23 javascript scala future promise scala.js

我试图在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

}
Run Code Online (Sandbox Code Playgroud)

我进入sbt fastOptJs:

[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] 
Run Code Online (Sandbox Code Playgroud)

我进入浏览器:

uncaught exception: java.lang.RuntimeException: System.getProperty() not implemented
Run Code Online (Sandbox Code Playgroud)

缺少什么/未实现?我该如何实现它?有解决方法吗?如何实现使用浏览器处理事件有意义的ExecutionContext?

sjr*_*jrd 32

自Scala.js 0.6.0起,global ExecutionContextScala 标准在Scala.js中可用.你可以用它导入它

import scala.concurrent.ExecutionContext.Implicits.global

// now you get to play with Futures
Run Code Online (Sandbox Code Playgroud)

在Scala.js中,它是别名scala.scalajs.concurrent.JSExecutionContext.Implicits.queue.此执行上下文将标准JavaScript事件循环中的作业排入队列.

请注意,任务是异步执行的,但不是并行执行的,因为JavaScript本身没有并行性概念.如果需要并行性,则需要使用Web Workers,但这些并不提供Futures 所需的共享内存模型.

适用于Scala.js <0.6.0的旧答案

有2个现有的和有效ExecutionContextscala.scalajs.concurrent.JSExecutionContext,在内部对象中有隐式版本Implicits.只需导入对你有意义的那个(可能queue,另一个实际上不是异步).

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue

// now you get to play with Futures
Run Code Online (Sandbox Code Playgroud)