如何在 Scala 中展平期货列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26717249/
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 flatten a List of Futures in Scala
提问by mikejones1477
I want to take this val:
我想拿这个 val:
val f = List(Future(1), Future(2), Future(3))
Perform some operation on it (I was thinking flatten)
对其执行一些操作(我在想展平)
f.flatten
And get this result
并得到这个结果
scala> f.flatten = List(1,2,3)
If the flatten method isn't appropriate here, that's fine. As long as I get to the result.
如果 flatten 方法在这里不合适,那也没关系。只要我得到结果。
Thanks!
谢谢!
回答by Gabriele Petronella
Future.sequencetakes a List[Future[T]]and returns a Future[List[T]].
Future.sequence接受 aList[Future[T]]并返回 a Future[List[T]]。
You can do
你可以做
Future.sequence(f)
and then use mapor onCompleteon it to access the list of values.
然后使用map或onComplete在它上面访问值列表。

![scala 使用喷雾 json 序列化 Map[String, Any]](/res/img/loading.gif)