gpt4 book ai didi

scala - Scala future 的理解失败

转载 作者:行者123 更新时间:2023-12-01 07:18:37 25 4
gpt4 key购买 nike

我有三个连续的 Futures 并在这样的理解中使用

val comF = for {
f1 <- future1
f2 <- future2
f3 <- future3
} yield {
// something
}

comF onSuccess { }
comF onFailure {
// ---------------- Here is the problem --------------------------------
//
// How do I know which future failed(throw exception), when the callback comes here ?
// Thanks for the help! Different futures using different exceptions can solve it.
}

现在我有一个像 List[Future[T]] 这样的 future 列表,首先我使用这个方法将它传输到 Future[List[T]] ( Why does this list-of-futures to future-of-list transformation compile and work? )。然后我得到了 future
val fList: Future[List[T]]
fList on Failure {
//
// How do I know which is Fail now >??
}

最佳答案

考虑代码:

def func = {
try {
val x = maybeThrows
val y = maybeThrowsToo
val z = maybeThrowsAsWell
result(x, y, x)
} catch (RuntimeException e) {
// How do I know which maybeThrows failed?
}
}
Future case 的工作原理基本相同。

甚至在 List 中进行分组计算没有帮助:
def func = {
try {
val x = maybeThrows
val y = maybeThrowsToo
val z = maybeThrowsAsWell
val list = List(x, y, z)
result(list)
} catch (RuntimeException e) {
// How do I know which maybeThrows failed?
}
}

剧透:您必须明确跟踪哪个计算失败。如果使用 try/catch 完成,会产生一些样板文件.但幸运的是 Future (和 Try )样板没有那么糟糕:
class TaggedException(val idx, exc: Exception)

def tagFailedWithIndex[T](idx: Int, f: Future[T]): Future[T] =
future recoverWith { case exc => Future.failed(new TaggedException(idx, exc)) }

val comF = for {
f1 <- tagFailedWithIndex(0, future1)
f2 <- tagFailedWithIndex(1, future2)
f3 <- tagFailedWithIndex(2, future3)
} yield something(f1, f2, f3)

comF onFailure {
case exc: TaggedException => "%d computation failed".format(exc.idx)
}

剧透,您必须明确跟踪哪个计算失败。如果用 try/catch 完成,会产生很多样板文件.但幸运的是有 Try , 和 Future行为更加相同:
class TaggedException(val idx, exc: Exception)

def tagFailedWithIndex[T](idx: Int, f: Future[T]): Future[T] =
future recoverWith { case exc => Future.failed(new TaggedException(idx, exc)) }

val comF = for {
f1 <- tagFailedWithIndex(0, future1)
f2 <- tagFailedWithIndex(1, future2)
f3 <- tagFailedWithIndex(2, future3)
} yield something(f1, f2, f3)

comF onFailure {
case exc: TaggedException => "%d computation failed".format(exc.idx)
}

关于scala - Scala future 的理解失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27945014/

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