繁体   English   中英

在另一个函数中播放Framework Action.async WS

[英]Play Framework Action.async WS within another function

使用Play 2.3将Web服务合并到Action中时,我遇到了一些难题。 在此“ ping”操作中,我首先检查请求者是否具有会话令牌。 如果它们这样做,则应用程序将字符串“ pong”返回给浏览器。

  def ping = Action { request =>
    request.session.get("token") match {
      case Some(token) => {
        Ok("pong")
      } case None => Unauthorized("error")  
    } 
  }

现在,如果在这样的操作中向另一个Web服务添加调用:

  def ping = Action.async { request =>
    request.session.get("email") match {
      case Some(email) => {
        WS.url("http://localhost:8080/ping").get.map { response =>
          Ok(response.json.as[JsString].value)
        }
      } case None => Unauthorized("error")  
    } 
  }

我最终不匹配,“无”(没有会话令牌的人)的匹配器不在Future中。

  type mismatch; found : play.api.mvc.Result required: scala.concurrent.Future[play.api.mvc.Result]

现在,我唯一的选择是摆脱开关中的“ ”。 编译器警告我该逻辑易于出错...但是它将进行编译。 我假设我在这里做错了一切,包括异步ws调用和会话变量处理。

谁能建议我如何解决此ping操作,以便它可以处理会话变量和异步开关。 我才刚刚开始掌握Scala并发/未来。

Action.async期望使用Future[Result] ,但是Unauthorized("error")只是一个Result 您可以通过使其成为成功的Future来解决此问题。

def ping = Action.async { request =>
    request.session.get("email") match {
        case Some(email) => {
            WS.url("http://localhost:8080/ping").get.map { response =>
                Ok(response.json.as[JsString].value)
            }
        } 
        case None => Future.successful(Unauthorized("error"))
    } 
}

case None替换为:

// ...
case None => Future.successful(Unauthorized("error"))

因此,在两种情况下,类型都将是结果的未来(成功返回HTTP错误作为结果)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM