简体   繁体   English

Scala.js 中的未来超时

[英]Timeout a Future in Scala.js

I need to place a timeout on a Future in a cross-platform JVM / JS application.我需要在跨平台 JVM / JS 应用程序中对 Future 设置超时。 This timeout would only be used in tests, so a blocking solution wouldn't be that bad.此超时仅用于测试,因此阻塞解决方案不会那么糟糕。

I implemented the following snippet to make the future timeout on JVM:我实现了以下代码片段以使 JVM 上的未来超时:

  def runWithTimeout[T](timeoutMillis: Int)(f: => Future[T]) : Future[T] =
      Await.ready(f, Duration.create(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS))

This doesn't work on Scala.js, as it has no implementation of Await .这不适用于 Scala.js,因为它没有Await的实现。 Is there any other solution to add a Timeout to a Future that works in both Scala.js and Scala JVM?是否有任何其他解决方案可以在 Scala.js 和 Scala JVM 中为 Future 添加超时?

Your code doesn't really add a timeout to the existing future.您的代码并没有真正为现有的未来添加超时。 That's not possible.那是不可能的。 What you're doing is setting a timeout for waiting for that future at that specific point.您正在做的是设置超时以在该特定时间等待该未来。 That, you can reproduce in a different, fully asynchronous way, by creating a future that will那,你可以通过创建一个未来的完全异步的方式来重现

  • resolve to f if it finishes within the given timeout如果它在给定的超时时间内完成,则解析为f
  • otherwise resolves to a failed TimeoutException否则解析为失败的TimeoutException
import scala.concurrent._
import scala.concurrent.duration.Duration

import scala.scalajs.js

def timeoutFuture[T](f: Future[T], timeout: Duration)(
    implicit ec: ExecutionContext): Future[T] = {
  val p = Promise[T]()
  val timeoutHandle = js.timers.setTimeout(timeout) {
    p.tryFailure(new TimeoutException)
  }
  f.onComplete { result =>
    p.tryComplete(result)
    clearTimeout(timeoutHandle)
  }
  p.future
}

The above is written for Scala.js.以上是为 Scala.js 编写的。 You can write an equivalent one for the JVM, and place them in platform-dependent sources.您可以为 JVM 编写一个等效的,并将它们放在与平台相关的源中。

Alternatively, you can probably write something equivalent in terms of java.util.Timer , which is supported both on JVM and JS.或者,您可以编写一些等效的java.util.Timer ,它在 JVM 和 JS 上都受支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM