2014-11-24 2 views
20

나는 Scala.js에서 Promises and Futures를 사용하려고했습니다. Promise works, Futures와 마자 경고와 오류가 발생합니다.Scala.js의 선물

시도 :

[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] 

을 그리고 브라우저에서 얻을 : 나는 SBT의 fastOptJs 얻을

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 

} 

그리고

uncaught exception: java.lang.RuntimeException: System.getProperty() not implemented 

없는 무엇/구현되어 있지 않은? 어떻게 구현할 수 있습니까? 해결 방법이 있습니까? 브라우저에서 이벤트를 처리하는 데 적합한 ExecutionContext를 구현하려면 어떻게해야합니까?

답변

27

Scala.js가 0.6.0이므로 Scala의 표준 globalExecutionContext을 Scala.js에서 사용할 수 있습니다. 당신은 Scala.js에서

import scala.concurrent.ExecutionContext.Implicits.global 

// now you get to play with Futures 

로 가져올 수 있습니다, 그것은 scala.scalajs.concurrent.JSExecutionContext.Implicits.queue에 대한 별칭입니다. 이 실행 컨텍스트는 표준 JavaScript 이벤트 루프에서 작업을 대기열에 포함시킵니다.

JavaScript는 병렬 처리의 개념 자체가 없으므로 작업은 비동기식으로 실행되지만 병렬로 실행되지 않습니다. 병렬 처리가 필요한 경우 Web Workers을 사용해야하지만 이들은 Future에 의해 요구되는 공유 메모리 모델을 제공하지 않습니다. < 0.6.0

는 내부 객체 Implicits에서 암시 버전으로, 기존 및 scala.scalajs.concurrent.JSExecutionContextExecutionContext의 작업 2있다 Scala.js을 신청

올드 대답. 자신에게 의미있는 것을 가져 오기 만하면됩니다 (아마도 queue, 실제로는 비동기가 아닙니다).

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

// now you get to play with Futures 
+0

짧은 연구 후에 [대기열]은 [promises] (https://www.promisejs.org/) 또는 [timeouts] (http://www.w3schools.com/)를 사용하여 구현됩니다. jsref/met_win_settimeout.asp). 약속을 지원하지 않는 오래된 브라우저의 경우. – Suma

+0

참고 :'queue'는 나중에 코드가 실행될 때 (비공개 또는 약속 시간 종료시 사용) 비동기식이지만 코드가 병렬로 실행되지 않습니다. 실제 "병렬"(동시) 작업을 수행하려면 웹 작업자가 필요합니다 (예 : github.com/nolanlawson/promise-worker의 라이브러리 사용). 아니면 내가 틀린거야? – Suma

+0

@Suma 네 말이 맞아. 자바 스크립트에는 공유 메모리 병렬 처리 같은 것이 없으므로 약속과 미래가 동시에 실행되지 않습니다. 병렬 처리가 필요한 경우 웹 작업자를 사용해야하지만 공유 메모리를 잃어 버리면 작업 자체가 근본적으로 바뀝니다. – sjrd