且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何等待Scala future的onSuccess回调完成?

更新时间:2021-10-15 08:25:48

不要使用onSuccess回调,而是在Future.map调用中产生副作用。这样,您就可以使用Future [Unit]。

Don't use an onSuccess callback, but instead do the side effect in a Future.map call. That way, you have a Future[Unit] to use Await on.

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{ Await, Future }

object Main {
  def main(args: Array[String]): Unit = {
    val f: Future[Int] = Future(0)
    val f2: Future[Unit] = f.map { x =>
      Thread.sleep(10000)
      println("The program waited patiently for this callback to finish.")
    }

    Await.ready(f2, Duration.Inf)
  }
}

请注意,如果要执行边仅在成功的情况下才有效(例如您的示例),请使用map。如果您还想在发生故障的情况下执行副作用,则使用正确的方法。在scala-user上查看Roland Kuhn的帖子

Note that if you want to execute a side effect only in case of success (like in your example), map is appropriate. If you want to execute a side effect also in case of failure, andThen is the right method to use. See this post from Roland Kuhn on scala-user.

另外,请 不要 在生产代码附近的任何地方使用Thread.sleep。

Also, please don't use Thread.sleep anywhere near production code.