鉴于整数以下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
因为f2
失败当输入整数为偶数(即2)。