如何解决 Scala 中的期货列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20012364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve a list of futures in Scala
提问by user2816456
I have a call that returns a Future. However, I need to make n calls so I will get back n futures. I am wondering how I would get the futures to all resolve before proceeding (without blocking the server)
我有一个返回 Future 的调用。但是,我需要打 n 个电话,这样我才能取回 n 个期货。我想知道如何在继续之前让期货全部解决(不阻塞服务器)
For example,
例如,
while(counter < numCalls){
val future = call(counter)
future.map{ x =>
//do stuff
}
counter += 1
}
//Now I want to execute code here after ALL the futures are resolved without
//blocking the server
回答by Leo
You can use Future.sequence(futureList)to convert a List[Future[X]]to a Future[List[X]]. And since the latter is just a simple Future, you can wait for it to finish with the help of the Await.readyor similar helpers.
您可以使用Future.sequence(futureList)将 a 转换List[Future[X]]为 a Future[List[X]]。由于后者只是一个简单的Future,您可以在Await.ready或类似帮助者的帮助下等待它完成。
So you would have to keep a list of the futures you generate. Something like:
因此,您必须保留一份您生成的期货清单。就像是:
val futures = new ListBuffer[Future[X]]
while(counter < numCalls) {
val future = call(counter)
futures += future
future.map { x =>
//do stuff
}
counter += 1
}
val f = Future.sequence(futures.toList)
Await.ready(f, Duration.Inf)
which you could also write as:
你也可以写成:
val futures = (1 to numCalls).map(counter => {
f = call(counter)
f.map(x => ...)
f
})
Await.ready(Future.sequence(futures), Duration.Inf)
回答by Christopher Hunt
A little more functional:
多一点功能:
val futures = for {
c <- 0 until 10
} yield {
val f = call(c)
f onSuccess {
case x =>
// Do your future stuff with x
}
f
}
Future.sequence(futures)
回答by wallnuss
I take it that you want to do something after the Futures are finished ,eg. a callback, without blocking the original call? Then you should do something like this:
我认为您想在期货完成后做某事,例如。回调,而不阻塞原始调用?那么你应该做这样的事情:
val futures = for (...) yield {
future {
...
}
}
val f = Future sequence futures.toList
f onComplete {
case Success(results) => for (result <- results) doSomething(result)
case Failure(t) => println("An error has occured: " + t.getMessage)
}
http://docs.scala-lang.org/overviews/core/futures.html
http://docs.scala-lang.org/overviews/core/futures.html
So you don't block with an await call, but you still wait for all Futures to complete and then do something on all results. The key aspects is using Future.sequence to join a lot of futures together and then to use a callback to act on the result.
所以你不会用 await 调用阻塞,但你仍然等待所有 Futures 完成,然后对所有结果做一些事情。关键是使用 Future.sequence 将许多期货连接在一起,然后使用回调对结果进行操作。

