如何使用Try

时间:2019-02-20 09:29:51

标签: scala akka future futuretask akka-actor

我有两个参与者,他们可以返回Result(在我的情况下是布尔值),也可以抛出异常,这是我的代码

val futureA: Future[Boolean] = ask(ActorA, MessageA(obj)).mapTo[Boolean]
val resultA = Await.result(futureA, timeout.duration) //can return boolean or throw an exception 

val futureB: Future[Boolean] = ask(ActorB, MessageB(obj)).mapTo[Boolean]
       val resultb = Await.result(futureB, timeout.duration)//can return boolean or throw an exception

我想在这里实现
场景1 ,如果futureA和FutureB成功,我应该得到类似(futureResponseA,futureResponseB)//(true,true)

场景2 如果futureA失败,则如果成功返回,则应继续执行FutureB,我应该得到类似(exceptionOfFutureA,resultofFutureB)

场景3 如果futureA成功返回而FutureB失败,我应该得到类似(futureResponseA,exceptionOfFutureB)

场景4 ,如果futureA和futureB都失败了,我应该得到类似(exceptionOfFutureA,exceptionOfFutureB)

我尝试过的       val futureA = ask(ActorA,MessageA(obj))。mapTo [Boolean]       val futureB = ask(ActorB,MessageB(obj))。mapTo [Boolean]

  val f = Try {Future.sequence(List(futureA, futureB))}
  val result = Await.result(f, Duration.Inf)

但我在此val result行上遇到了错误

found   : scala.util.Try[scala.concurrent.Future[List[Boolean]]]
[error]  required: scala.concurrent.Awaitable[?]

如何归档这些扫描仪,请指导

1 个答案:

答案 0 :(得分:3)

Try不是AwaitableFuture不会引发异常,但是Await可以。因此,您需要用Await包装Try,并且由于要捕获一个或两个故障,所以这意味着2个不同的Await

val resultTuple = (Try(Await.result(futureA, Duration.Inf))
                  ,Try(Await.result(futureB, Duration.Inf)))

结果类型为Tuple2[Try[Boolean],Try[Boolean]],它涵盖了您列出的4种情况:(成功,成功)(成功,失败)(失败,成功)(失败,失败)