Scala Futures - flatMap 和 onFailure

标签 scala monads future

如果我有一些计算需要一段时间,我可能会把它放在 scala.concurrent.Future 中:

val f = Future { someLongRunningFunction() }

假设我想在计算完成后异步执行其他操作:

f.flatMap{ _ => anotherLongRunningFunction() }

如果 f 的初始 block 失败,我如何在使用 flatMap 或其他组合器时“惯用地”处理这个问题?仅仅是在 flatMap 之前使用 recoveronFailure 的情况吗?

我喜欢使用 flatMap 的优雅和简单,但似乎失败场景妨碍了它。

编辑:第二个 future 依赖于第一个,因此是flatMap。我正在寻找一种解决方案,它可以让我像使用 flatMap 一样优雅地链接,但也可以处理第一个失败。

最佳答案

flatMap 引用 scaladoc :

Creates a new future by applying a function to the successful result of this future, and returns the result of the function as the new future. If this future is completed with an exception then the new future will also contain this exception.

注意粗体,这意味着您传递给 flatMap 的任何内容都只会在初始 future 成功完成时执行。

所以你应该只处理整个执行的结果:

val result = future1.flatMap {
    result => functionReturningFuture2(result)
}

然后:

result.onFailure // or
result.onSuccess // or
result.recover

关于Scala Futures - flatMap 和 onFailure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30169639/

相关文章:

Haskell:如果遍历参数,RWS 上的单子(monad)固定点将循环

java - Akka java 永远不会关闭 ActorRef

rust - 有没有办法可以将 futures 0.1 转换为标准库 futures?

scala - sbt-assembly 的自定义输出路径

python - 访问 WrappedArray 元素

scala - 如何在scala中使用flink折叠功能

Haskell笛卡尔积,带过滤器的Monad

scala - 使用 Scalaz Functor 进行 7 元函数的编译错误

scala - 纯函数随机数生成器 - 状态单子(monad)

scala - future [A] 与 future [Throwable\/A]