Scala在try block中解决期货

时间:2018-07-20 18:56:43

标签: scala

考虑以下Scala try catch finally示例:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object Test extends App {

  try {
    val futureResponses = Future(List("200", "200", "500", "600"))
    println("in TRY block...")
    futureResponses.map{responses =>
      responses.forall(_ == 200) match {
        case true => println("Successfully Finished the Requets")
        case false => println("Failed when fetching requests")
      }}
  }
  catch {
    case e: Exception => e.printStackTrace()
  }
  finally {
    println("finally thing...")
  }
}

finally块是在Try块中解决期货并输出之前执行的

in TRY block...
finally thing...

如何等待try块解决期货问题

1 个答案:

答案 0 :(得分:1)

您实际上并不需要try块,在函数式编程中不建议这样做。您可以使用future.onComplete。如果您确实需要使用Try {}

使用onComplete成功实现未来的示例,

scala> import scala.concurrent.Future
import scala.concurrent.Future

scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global

scala>     Future(List("200", "200", "500", "600")).map { responses =>
     |       responses.forall(_ == 200) match {
     |         case true => println("Successfully Finished the Requets")
     |         case false => println("\nFailed when fetching requests")
     |       }
     |     } onComplete (res => println(s"finally thing... + $res"))

Failed when fetching requests
finally thing... + Success(())

例如,当未来失败时,

scala>     Future(List("200", "200", "500", "600")).map { responses =>
     |       responses.map(r => r.toInt / 0)
     |     } onComplete (res => println(s"finally thing... + $res"))

scala> finally thing... + Failure(java.lang.ArithmeticException: / by zero)