【问题标题】:How to make internal synchronous post request in Play framework and scala?如何在 Play 框架和 Scala 中进行内部同步发布请求?
【发布时间】:2016-02-19 17:25:00
【问题描述】:

我是 Play 和 Scala 的新手。我正在尝试使用 Play 和 Scala 构建应用程序。我需要在内部进行 post call 以从我的服务器获取数据。但这应该是同步的。从这个发布请求中获取数据后,我需要将该数据发送到前端。我见过很多资源,但都是异步的。请帮帮我。

我正在从 DB 获取数据,然后应该将数据作为响应返回。

数据库位于远程服务器而不是托管服务器。

【问题讨论】:

  • Play 的动作默认和设计是异步的。为什么要同步? “发送到前端”到底是什么意思? Future[JsValue] 可以完美地在动作中使用,一旦可用就会“发送”给客户端。

标签: scala post playframework


【解决方案1】:

我认为无论如何你都不应该阻止。

def action = Action.async {
  WS.url("some url")
    .post(Json.toJson(Map("query"->query)))
    .map { response => 
      val jsonResponse = response.json
      // in this place you have your response from your call
      // now just do whatever you need to do with it,
      // in this example I will return it as `Ok` result
      Ok(jsonResponse)
    }
}

只需映射您的调用结果并在 Future 的上下文中对其进行修改,然后使用带有 FutureAction.async

如果你真的想阻止使用Await.result(future, 5 seconds),导入

import scala.concurrent.duration._
import scala.concurrent.Await

See docs for Await here

【讨论】:

    【解决方案2】:

    所有请求都是异步的,但没有什么可以阻止您在代码中等待带有 await 的响应。

    val response = await(yourFutureRequest).body
    

    上面写的那行会阻塞,直到future结束。

    【讨论】:

    • val future:Future[JsValue] = WS.url("some url").post(Json.toJson(Map("query"->query))).map{ response=> response .json} 你的建议没有奏效。我得到应用程序不带参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2018-09-04
    • 2022-07-06
    • 2017-11-14
    • 2015-01-20
    • 2018-03-05
    相关资源
    最近更新 更多