【发布时间】:2020-08-12 03:29:18
【问题描述】:
我有一个场景,我想计算嵌套的期货。下面是场景:
def firstFuture(factor: Int): Future[Int] = Future {
println("Running future 1")
Thread.sleep(3000)
5 * factor
}
def secondFuture(factor: Int) = Future {
println("Running future 2")
throw new Exception("fjdfj")
Thread.sleep(4000); 3 * factor
}
def thirdFuture = Future {
println("Running future 3")
Thread.sleep(5000)
throw new Exception("mai fat raha hu")
}
def method = {
(Future(5).map { factor =>
firstFuture(factor).recover { case ex: Exception => throw new Exception("First future failed") }
secondFuture(factor).recover { case ex: Exception => throw new Exception("Second future failed") }
thirdFuture.recover { case ex: Exception => throw new Exception("Third future failed") }
}).flatMap(identity).recover { case ex: Exception =>
println("Inside recover")
println(ex.getMessage)
}
}
Await.result(method, 20 seconds)
我想处理主要未来完成的所有嵌套未来的异常。假设如果 secondFuture 失败,那么结果应该是 secondFuture 失败。但我只是在第三个未来得到反映。我怎样才能做到这一点。应该如何实现。
注意:嵌套的三个期货应该并行运行。
【问题讨论】:
标签: scala error-handling future