运行返回异步尝试的函数

时间:2019-06-30 09:02:22

标签: scala error-handling concurrency future

假设我有foo: A => Try[B],并想与Future异步运行它,例如:

import scala.util.Try
import scala.concurrent.{Future, ExecutionContext}

def foo(s: String): Try[Int] = Try(s.toInt)
def futureFoo(s: String)(implicit ec: ExecutionContext): Future[Int] = Future(foo(s).get)

由于我不喜欢使用get方法,因此我要像这样重写futureFoo

def futureFoo(s: String)(implicit ec: ExecutionContext): Future[Int] =
  Future(foo(s)).flatMap(Future.fromTry)

这有意义吗?我错过了帮助功能的功能吗?

1 个答案:

答案 0 :(得分:3)

考虑像这样折叠get,使Try的含义更加明确

Future(foo(s).fold(throw _, identity))

尽管在美学上会造成破坏,但是在get内调用Future应该是安全的,

Future(foo(s).get)

因为Future内部使用Try来处理抛出。例如,

def foo(s: String): Try[Int] = Try(throw new RuntimeException("boom!"))
def futureFoo(s: String): Future[Int] = Future(foo(s).get)
futureFoo("foo") andThen { case e => println(e) }

输出

Failure(java.lang.RuntimeException: boom!)