簡體   English   中英

在Play框架中結合Scala中不同類型的期貨

[英]Combining Futures of different types in Scala in Play Framework

我的方法中有一些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...")

       )

   }
}

嘗試:

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

您可以使用以下方式進行理解:

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

您也可以將Futures放在一個列表中,該列表將生成一個期貨列表,然后使用Future.sequence(your list)來獲取一個Future of list而不是一個期貨列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM