scala - 将尝试转换为 future 并恢复为 future

标签 scala concurrency future

我有一个 Try抛出异常。我想要那个 Try成为Future这样我就可以 recoverWith .
我如何转换 TryFuture不处理 Try 中的任何异常(只是在 future 与恢复)?
请注意,需要使用 Await 来测试您 future 的结果
代码示例演示了我的想法,但一旦达到它也会抛出(new RuntimeException("-------failed-------") 是我得到的)

val t = Try(throw new RuntimeException("my"))

val resF : Future[String] = if (t.isSuccess)
  Future.successful(t.get)
else
  Future.failed(new RuntimeException("-------failed-------"))

val resFWithRecover = resF.recoverWith{
  case NonFatal(e) =>
    Future.successful("recoveredWith")
}
Await.result(resFWithRecover, Duration("5s"))

最佳答案

... how do convert Try to Future without handling any exception in the Try?



使用 Future.fromTry .
scala> val t = Try(throw new RuntimeException("my"))
t: scala.util.Try[Nothing] = Failure(java.lang.RuntimeException: my)

scala> val resF = Future.fromTry(t)
resF: scala.concurrent.Future[Nothing] = scala.concurrent.impl.Promise$KeptPromise@57cf54e1

scala> resF.recoverWith{
     |   case NonFatal(e) =>
     |     Future.successful("recoveredWith")
     | }
res5: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@1b75c2e3

关于scala - 将尝试转换为 future 并恢复为 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581921/

相关文章:

java - 并发:在自定义连接池中实现连接超时

java - 通过拆分和运行将 ListenableFuture<Iterable<A>> 转换为 Iterable<ListenableFuture<B>>

scala - 为什么我们需要 Future 和 Promise?

stream - 我如何每 N 秒从无界队列中提取消息并将它们生成到 Tokio 处理程序?

scala - 如何在scala中定义一个函数不返回或返回void

java - 定义一个与 scala 中的类同名的方法是否安全?

java - 使用 Java/Scala 将 Markdown 转换为 HTML

java - 相同的条件逻辑为 Java 中的 AtomicBoolean 生成两个截然不同的字节码。为什么?

scala - "r0"、 "r1"等在 Scala 中有特殊含义吗?

java - 您如何知道 Future 对象何时完成其任务?