等待未来,得到一个 [英] Await a future, receive an either

查看:57
本文介绍了等待未来,得到一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想等待一个可能失败的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.catchingf 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调用,因此可以安全地假设valueSome.然后,只需在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆