在Play框架中结合Scala中不同类型的Futures

时间:2014-04-08 14:23:31

标签: scala playframework parallel-processing

我在方法中有一些scala代码,如下所示:

def testMethod = Action {

   val future1: Future[List[A]] = methodA()
   val future2: Future[List[String]] = methodB()
   val future3: Future[List[B]] = methodC()

   Ok("Testing...")
}

如何将它们组合成一个单独的未来,以便我可以返回异步结果,如:

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...")

       )

   }
}

2 个答案:

答案 0 :(得分:1)

尝试:

val combinedFuture = Future.sequence(List(future1,future2,future3))

答案 1 :(得分:1)

你可以使用像这样的For-comprehensions:

val combinedFuture: Future[(List[A],List[String],List[B])] = for{
   l1 <- future1,
   l2 <- future2,
   l3 <- future3
}yield{
   (l1, l2, l3)
}

你也可以把你的期货放在一个列表中,这列出一个期货清单,然后使用Future.sequence(your list)来获得未来的清单而不是期货清单。

相关问题