/
QueueExecutionContext.scala
63 lines (52 loc) · 1.56 KB
/
QueueExecutionContext.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* Scala.js (https://www.scala-js.org/)
*
* Copyright EPFL.
*
* Licensed under Apache License 2.0
* (https://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.scalajs.concurrent
import scala.concurrent.ExecutionContextExecutor
import scala.scalajs.js
import scala.scalajs.js.|
object QueueExecutionContext {
def timeouts(): ExecutionContextExecutor =
new TimeoutsExecutionContext
def promises(): ExecutionContextExecutor =
new PromisesExecutionContext
def apply(): ExecutionContextExecutor =
if (js.typeOf(js.Dynamic.global.Promise) == "undefined") timeouts()
else promises()
private final class TimeoutsExecutionContext extends ExecutionContextExecutor {
def execute(runnable: Runnable): Unit = {
js.Dynamic.global.setTimeout({ () =>
try {
runnable.run()
} catch {
case t: Throwable => reportFailure(t)
}
}, 0)
}
def reportFailure(t: Throwable): Unit =
t.printStackTrace()
}
private final class PromisesExecutionContext extends ExecutionContextExecutor {
private val resolvedUnitPromise = js.Promise.resolve[Unit](())
def execute(runnable: Runnable): Unit = {
resolvedUnitPromise.`then` { (_: Unit) =>
try {
runnable.run()
} catch {
case t: Throwable => reportFailure(t)
}
(): Unit | js.Thenable[Unit]
}
}
def reportFailure(t: Throwable): Unit =
t.printStackTrace()
}
}