免责声明:下面的代码片段与正在进行的 Coursera 课程之一有关。让我们认为它只是为了学习目的而发布的,不应该用于提交作为家庭作业的解决方案。
正如下面的评论所述,我们需要将 Future 列表转换为列表的单个 Future。不仅如此,如果至少有一个输入期货失败,则生成的未来应该失败。
我遇到了以下实现,我不完全理解。
/** Given a list of futures `fs`, returns the future holding the list of values of all the futures from `fs`.
* The returned future is completed only once all of the futures in `fs` have been completed.
* The values in the list are in the same order as corresponding futures `fs`.
* If any of the futures `fs` fails, the resulting future also fails.
*/
def all[T](fs: List[Future[T]]): Future[List[T]] =
fs.foldRight(Future(Nil:List[T]))((f, fs2) =>
for {
x <- f
xs <- fs2
} yield (x::xs))
特别是,我不明白其中的以下内容:
Future[T] -> T
转变发生在哪里?它看起来xs <- fs2
是我们唯一接触 initial 的地方Futures
,每种xs
类型都应该是Future[T]
(但不知何故它变成了 justT
)。- 故障如何处理?当其中一个输入失败时,结果
Future
对象似乎确实失败了Futures
。