等待未来,得到一个 [英] Await a future, receive an either
问题描述
我想等待一个可能失败的scala未来.如果我使用Await.result
,将引发异常.相反,如果我有f: Future[String]
,我想使用方法Await.resultOpt(f): Option[String]
或Await.resultEither(f): Either[String]
.
I'd like to await a scala future that may have failed. If I use Await.result
the exception will be thrown. Instead, if I have f: Future[String]
I would like a method Await.resultOpt(f): Option[String]
or Await.resultEither(f): Either[String]
.
我可以使用scala.util.control.Exception.catching
或f map (Right(_)) recover { case t: Throwable => Left(t) }
来获取,但是必须有更直接的方法.
I could get this by using scala.util.control.Exception.catching
or I could f map (Right(_)) recover { case t: Throwable => Left(t) }
, but there must be a more straightforward way.
推荐答案
您可以使用Await.ready
,它只是阻塞,直到Future成功或失败,然后再返回对该Future的引用.
You could use Await.ready
which simply blocks until the Future has either succeeded or failed, then returns a reference back to that Future.
从那里,您可能想要获得Future的value
,它是一个Option[Try[T]]
.由于Await.ready
调用,因此可以安全地假设value
是Some
.然后,只需在Try[T]
和Either[Throwable, T]
之间映射即可.
From there, you would probably want to get the Future's value
, which is an Option[Try[T]]
. Due to the Await.ready
call, it should be safe to assume that the value
is a Some
. Then it's just a matter of mapping between a Try[T]
and an Either[Throwable, T]
.
简短版本:
val f: Future[T] = ...
val result: Try[T] = Await.ready(f, Duration.Inf).value.get
val resultEither = result match {
case Success(t) => Right(t)
case Failure(e) => Left(e)
}
这篇关于等待未来,得到一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!