gpt4 book ai didi

Scala 理解 : How to Recover and Continue If a Future Fails

转载 作者:行者123 更新时间:2023-12-02 06:55:11 24 4
gpt4 key购买 nike

鉴于以下 List 整数...

val l = List(1, 2, 3)

...我需要调用 2 个在每个元素上返回 Future 的方法并获得以下结果:

Future(Some(1), Some(2), Some(3))

下面是我的尝试:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def f1(i: Int) = Future(i)
def f2(i: Int) = Future { if (i % 2 == 0) throw new Exception else i }

val l = List(1, 2, 3)

val results = Future.sequence(l.map { i =
val f = for {
r1 <- f1(i)
r2 <- f2(i) // this throws an exception if i is even
} yield Some(r1)

f.recoverWith {
case e => None
}
})

如果 f2 失败,我想恢复并继续处理剩余的元素。上面的代码不起作用,因为永远不会调用 recoverWith,即使 f2 失败。

f2 失败时如何恢复,最终的结果是这样的?

Future(Some(1), None, Some(3))

第二个元素应该是 None 因为当输入整数为偶数(即 2)时 f2 失败。

最佳答案

recoverWith 的输出类型为 Future 时,它可以正常工作。

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def f1(i: Int) = Future(i)
def f2(i: Int) = Future { if (i % 2 == 0) throw new Exception else i }

val l = List(1, 2, 3)

val results = Future.sequence(l.map { i =>
val f = for {
r1 <- f1(i)
r2 <- f2(i) // this might throw an exception
} yield Some(r1)

f.recoverWith {
case e => Future { println("Called recover " + i); None } // wrapped in Future
}
})
results onComplete println

结果:

// Called recover 2
// Success(List(Some(1), None, Some(3))

// tried with scala version: 2.10.4

关于Scala 理解 : How to Recover and Continue If a Future Fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935228/

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