计算期货的列表,并返回未来的结果 [英] Calculate the list of the futures and and return the result future
问题描述
我有一个函数,它需要期货未来[A] *
,我想要返回 Future [List [A] code>。
I have a function which takes futures Future[A]*
and I want it to return a Future[List[A]]
.
def singleFuture[T](futures: List[Future[A]]): Future[List[A]] = {
val p = Promise[T]
futures filter { _ onComplete { case x => p complete x /*????*/ } }
p.future
}
$ b b
我还希望类型 Future [List [A]]
的结果未来在列表future之后立即完成 List [Future [ A]]
已完成。
And I also want the result future of type Future[List[A]]
becomes completed immediately after the list futures List[Future[A]]
have been completed.
该代码无效。我想我应该使用 flatMap
这里,因为应该有2个内部循环:一个用于未来,一个用于promise。但是如何?
That code doesn't work. I figure I should use flatMap
here because there should be 2 internal loops: one for the future and one for promise. But how?
我不想在这里使用的理解,因为我想了解更深的杠杆。 p>
I'd like not use for comprehension here because I'd like to understand the process at the deeper lever.
推荐答案
您可以使用foldRight来实现:
You can use foldRight to achieve this:
def singleFuture[A](futures: List[Future[A]]): Future[List[A]] = {
val p = Promise[List[A]]()
p.success(List.empty[A])
val f = p.future // a future containing empty list.
futures.foldRight(f) {
(fut, accum) => // foldRight means accumulator is on right.
for {
list <- accum; // take List[A] out of Future[List[A]]
a <- fut // take A out of Future[A]
}
yield (a :: list) // A :: List[A]
}
}
未来的期货列表失败,一个< - 未来将失败,导致累积被设置为失败的未来。
if any future in futures list fails, a <- fut will fail, resulting in accum being set to failed future.
如果你想避免使用for,你可以展开它到flatMap如下:
If you want to avoid using for, you can either expand it to flatMap as follows:
accum.flatMap( list => fut.map(a => a :: list))
或者你可以使用async-await(注意它还是一个实验性功能)。
Or you can use, async-await (noting that it is still an experimental feature).
def singleFuture[T](futures: List[Future[T]]): Future[List[T]] = async {
var localFutures = futures
val result = ListBuffer[T]()
while (localFutures != Nil) {
result += await { localFutures.head }
localFutures = localFutures.tail
}
result.toList
}
这篇关于计算期货的列表,并返回未来的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!