斯卡拉,游戏,期货:结合多个期货的结果

时间:2013-02-24 00:57:49

标签: scala asynchronous playframework future playframework-2.1

我正在使用:

  • Scala 2.10
  • 播放2.1

目前,我正在使用Future中的scala.concurrent._类,但我愿意尝试其他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模板。

现在,我试图在getSearchResult(String, Int)循环中调用for来获取几个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

1 个答案:

答案 0 :(得分:11)

创建由List或其他Result类型集合参数化的Future。

来自here

在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)
相关问题