我有一个代码(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))
因为如果您在Future
上Await.result
,它将在成功时返回值,或者抛出由失败的Future
捕获的异常。