gpt4 book ai didi

Scala Futures - flatMap 和 onFailure

转载 作者:行者123 更新时间:2023-12-01 22:29:35 25 4
gpt4 key购买 nike

如果我有一些计算需要一段时间,我可能会把它放在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com