[英]Combining Futures of different types in Scala in Play Framework
I have some scala code in a method that looks like : 我的方法中有一些scala代码,如下所示:
def testMethod = Action {
val future1: Future[List[A]] = methodA()
val future2: Future[List[String]] = methodB()
val future3: Future[List[B]] = methodC()
Ok("Testing...")
}
How do I combine them together into a single future so that I can return an Async Result like: 如何将它们组合在一起形成一个单一的未来,以便可以返回如下所示的异步结果:
def testMethod = Action {
val future1: Future[List[A]] = methodA()
val future2: Future[List[String]] = methodB()
val future3: Future[List[B]] = methodC()
val combinedFuture: Future[(List[A],List[String],List[B])] // the single Future needed
Async {
combinedFuture.map( item =>
Ok("It is done...")
)
}
}
尝试:
val combinedFuture = Future.sequence(List(future1,future2,future3))
You could use For-comprehensions like this: 您可以使用以下方式进行理解:
val combinedFuture: Future[(List[A],List[String],List[B])] = for{
l1 <- future1,
l2 <- future2,
l3 <- future3
}yield{
(l1, l2, l3)
}
You could also put your Futures in a list, which makes a list of futures, then use Future.sequence(your list)
to get a Future of list instead of a list of futures. 您也可以将Futures放在一个列表中,该列表将生成一个期货列表,然后使用Future.sequence(your list)
来获取一个Future of list而不是一个期货列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.