简体   繁体   中英

Combining Futures of different types in Scala in Play Framework

I have some scala code in a method that looks like :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM