如何验证 Future[List[T]] 中的单个元素以返回 Future[List[T]] 或抛出异常



这里不需要注意函数的目的,它只是为了演示:

def readAllByPersonOrFail(person: Person, otherPersonId: Long): Future[List[Person]] = {
val personSiblingsFuture: Future[List[Person]] = personSiblingsDomain.readAllByPersonId(person.id)
personSiblingsFuture.map { persons =>
persons.find(_.id == otherPersonId) match {
case Some(person) =>
person.isActive match {
case true => person
case false => throw new IllegalArgumentException("something inactive")
}
case None => throw new IllegalArgumentException("something wrong ehre")
}
}
personSiblingsFuture
}

我想返回上面的人兄弟姐妹未来,如果它验证(确保正确的人在列表中并且处于活动状态),否则抛出异常。 我不认为上面的代码在做正确的事情,因为它在失败时不存在。

看看scala.concurrent.Future.map.这创造了一个新的未来,其价值是通过将函数应用于这个未来的成功结果来解决的。

请注意,在这里,您也扔掉了您刚刚用.map()创造的未来。

有几个方面可以解决您的问题,尽管您应该更深入地质疑异常的使用Futures。Scala 专门提供了FutureOptionTry等概念,以避免抛出异常并具有更清晰的控制流。

选项 1,返回映射的未来

在你的函数中,

def func(...): Future[List[Person]] {
val personSiblingsFuture = ...;
personSiblingsFuture.map { persons =>
...
}
}
// note we're not returning personSiblingsFuture,
// but the mapped result

当有人真正试图获得未来的价值时,例如通过使用.value,他们可能会看到一个异常:

def main() {
val future = func(...);  // this is fine
val my_list = future.value;  // awaits Future, might throw here
}

选项 2,实际上等待列表并加入函数

返回一个可能抛出的未来很奇怪,如果你实际上明确地有一个可能抛出的函数,可能会更容易一些,例如

/** jsdoc describing function **/
def funcMightThrow(...): List[Person] {
val personSiblingsFuture = ...;
val personSiblings = personSiblingsFuture.value;
personSiblings.find(_.id == otherPersonId) match {
case Some(person) =>
person.isActive match {
case true => personSiblings
case false => throw new IllegalArgumentException("something inactive")
}
case None => throw new IllegalArgumentException("something wrong ehre")
}
}

选项 3,考虑使返回类型更明确

def func(...): Future[Try[List[Person]]] {
val personSiblingsFuture = ...;
personSiblingsFuture.map { persons =>
...
// successful case returns 'persons' (List[Person])
// fail cases return Failure(...) instead
}
}  // return the mapped future

您还可以通过使用.value返回Try[List[Person]]而不是其中的Future[],这使func成为阻塞函数。

相关内容

最新更新