我在跨平台的JVM / JS应用程序中拥有未来。在JVM中按照以下方式轮询未来:
class MyColumn extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: Container(
alignment: Alignment.center,
height: 50.0,
width: double.infinity,
color: Colors.yellow,
child: Text(
'Anything want on top',
textAlign: TextAlign.center,
),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
color: Colors.red,
child: Text(
'Anything want in the middle',
textAlign: TextAlign.center,
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
alignment: Alignment.center,
height: 75.0,
width: double.infinity,
color: Colors.blue,
child: Text(
'Anything want in the bottom',
textAlign: TextAlign.center,
),
),
),
],
),
);
}
}
这不适用于Scala.js,因为Scala.js没有实现val load = Future(loadSometing())
if (load.isCompleted) {
val loaded = Await.result(load, Duration.Inf)
// now process it
}
。但就我而言,我不是在使用Await等待,只是为了获得我知道的结果。我知道一种适当的解决方案是使代码完全异步并在Await
处理程序(映射或onComplete)中执行处理,但是即使知道这不是一种适当的方法,也可以对Future
结果进行轮询在Scala.js中以某种方式出现?
答案 0 :(得分:3)
使用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))