[英]scala, play, futures: combining results from multiple futures
我在用:
目前,我正在使用scala.concurrent._
的Future
類,但我願意嘗試另一個API。
我無法將多個期貨的結果合並到一個List [(String,String)]中。
以下Controller
方法成功將單個Future的結果返回到HTML模板:
def test = Action { implicit request =>
queryForm.bindFromRequest.fold(
formWithErrors => Ok("Error!"),
query => {
Async {
getSearchResponse(query, 0).map { response =>
Ok(views.html.form(queryForm,
getAuthors(response.body, List[(String, String)]())))
}
}
})
}
方法getSearchResult(String, Int)
執行Web服務API調用並返回Future [play.api.libs.ws.Response]。 方法getAuthors(String, List[(String, String)])
將List [(String,String)]返回給HTML模板。
現在,我試圖在for
循環中調用getSearchResult(String, Int)
來獲取幾個Response主體。 以下內容應該說明我正在嘗試做什么,但是我得到了一個編譯時錯誤:
def test = Action { implicit request =>
queryForm.bindFromRequest.fold(
formWithErrors => Ok("Error!"),
query => {
Async {
val authors = for (i <- 0 to 100; if i % 10 == 0) yield {
getSearchResponse(query, i)
}.map { response =>
getAuthors(response.body, List[(String, String)]())
}
Ok(views.html.form(queryForm, authors))
}
})
}
類型不匹配; found:scala.collection.immutable.IndexedSeq [scala.concurrent.Future [List [(String,String)]]] required:List [(String,String)]
如何將多個Future
對象的響應映射到單個Result
?
創建由List或Result類型的其他Collection參數化的Future。
從這里 :
在Play 1中,您可以這樣做:
F.Promise<List<WS.HttpResponse>> promises = F.Promise.waitAll(remoteCall1, remoteCall2, remoteCall3);
// where remoteCall1..3 are promises
List<WS.HttpResponse> httpResponses = await(promises); // request gets suspended here
在Play 2中不那么直接:
val httpResponses = for {
result1 <- remoteCall1
result2 <- remoteCall2
} yield List(result1, result2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.