Scala.我如何从Future获得成功、失败和抛出异常的价值



我有一个代码(getServiceBySid函数返回Future[ServiceCategory](:

var service: ServiceCategory =
Await.result((for {
optService <- getServiceBySid(serviceSid)
} yield {
optService
}) recover {
case e: Throwable =>
throw e
}, Duration(10, TimeUnit.SECONDS))

我一直在想,这段代码不是真正的Scala风格。实际上,它的作用类似

val serviceCategory: ServiceCategory = 
getServiceCategoryBySid(serviceCategorySid) onComplete {
case Success(value) => value
case Failure(e) => throw e
}

但是onComplete返回Unit,所以它不起作用。如何重构代码?

您可以简单地编写

Await.result(getServiceBySid(serviceSid), Duration(10, TimeUnit.SECONDS))

因为如果您在FutureAwait.result,它将在成功时返回值,或者抛出由失败的Future捕获的异常。

最新更新