等待数量未知的期货 [英] Wait for an unknown number of futures
问题描述
在Scala 2.10中,写一个返回期货的函数的正确方法是什么?当列表中的所有期货都完成时,该函数会完成?
In Scala 2.10, what is a correct way to write a function that returns a future which completes when all futures in a list complete?
经过研究和实验,我在Scala工作表中开发了以下代码:
After researching and experimenting, I have developed the code below, in a Scala Worksheet:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent._
object ws2 {
def executeFutures(futures: Seq[Future[Unit]]): Future[Unit] = {
def cascadeFutures(futureSeq: Seq[Future[Unit]], f: Future[Unit]): Future[Unit] = {
futureSeq match {
case h :: t => h.flatMap { u => cascadeFutures(t, f) }
case nil => f
}
}
cascadeFutures(futures, Future {})
} //> executeFutures: (futures: Seq[scala.concurrent.Future[Unit]])scala.concurren
//| t.Future[Unit]
Await.ready(executeFutures(Seq(
Future { println("Future1") },
Future { println("Future2") },
Future { println("Future3") }
)) , 2.seconds) //> Future1
//| Future2
//| Future3
//| res0: awaitable.type = scala.concurrent.impl.Promise$DefaultPromise@2dd063b3
//|
}
我不确定此代码是否正确,或者不确定是否有更好的方法.
I'm not sure that this code is correct, or, even if it's correct, if there is a better way.
如果期货是串行执行而不是并行执行,这不是问题.
It's not a problem if the futures are executed serially instead of in parallel.
此问题与等待几种期货不同,后者处理已知数量的期货.
This question is different from Wait for several Futures, which deals with a known number of futures.
推荐答案
使用 Future.sequence
将期货列表[T]转换为单个列表期货[T].
Use Future.sequence
to turn a List of Futures[T] into a single Future of List[T].
val listOfFutures:List[Future[T]] = ...
val futureOfList:Future[List[T]] = Future.sequence(listOfFutures)
这不仅适用于List
,而且适用于任何 TraversableOnce ,其中包括大部分(如果不是全部)的scala.collections
.
This works, not just for List
s, but for any TraversableOnce, which includes most, if not all, of scala.collections
.
这篇关于等待数量未知的期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!