[英]scala, play, futures: combining results from multiple futures
I am using: 我在用:
Currently, I am using the Future
class from scala.concurrent._
, but I'm open to trying another API. 目前,我正在使用
scala.concurrent._
的Future
类,但我愿意尝试另一个API。
I am having trouble combining the results of multiple futures into a single List[(String, String)]. 我无法将多个期货的结果合并到一个List [(String,String)]中。
The following Controller
method successfully returns the results of a single Future to an HTML template: 以下
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)]())))
}
}
})
}
The method getSearchResult(String, Int)
performs a web service API call and returns a Future[play.api.libs.ws.Response]. 方法
getSearchResult(String, Int)
执行Web服务API调用并返回Future [play.api.libs.ws.Response]。 The method getAuthors(String, List[(String, String)])
returns a List[(String, String)] to the HTML template. 方法
getAuthors(String, List[(String, String)])
将List [(String,String)]返回给HTML模板。
Now, I am trying to call getSearchResult(String, Int)
in a for
loop to get several Response bodies. 现在,我试图在
for
循环中调用getSearchResult(String, Int)
来获取几个Response主体。 The following should give an idea of what I'm trying to do, but I get a compile-time error: 以下内容应该说明我正在尝试做什么,但是我得到了一个编译时错误:
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))
}
})
}
type mismatch; 类型不匹配; found : scala.collection.immutable.IndexedSeq[scala.concurrent.Future[List[(String, String)]]] required: List[(String, String)]
found:scala.collection.immutable.IndexedSeq [scala.concurrent.Future [List [(String,String)]]] required:List [(String,String)]
How can I map the responses of several Future
objects to a single Result
? 如何将多个
Future
对象的响应映射到单个Result
?
Create a Future parametrized by a List or other Collection of the Result type. 创建由List或Result类型的其他Collection参数化的Future。
In Play 1 you can do this: 在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
In Play 2 less direct: 在Play 2中不那么直接:
val httpResponses = for {
result1 <- remoteCall1
result2 <- remoteCall2
} yield List(result1, result2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.