在Scala.js中轮询未来

时间:2018-12-14 14:29:49

标签: scala asynchronous future scala.js

我在跨平台的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中以某种方式出现?

1 个答案:

答案 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))

Fiddle here