【问题标题】:Play framework - Using WS API播放框架 - 使用 WS API
【发布时间】:2014-08-28 09:59:15
【问题描述】:

我必须从我的 Scala Play 框架应用程序调用外部 REST 服务。使用 WS API,我得到了一个 Future,但不确定哪个是从这个 Future 中“提取”价值的最佳方式。这是我的代码:

val externalRestServiceCall: Future[List[Data]] = WS.clientUrl(dataSourceProperties.url).get().map {
  response => response.json.as[List[Data]]
}

这是我目前的方法,虽然返回一个 Future:

val timeoutFuture = play.api.libs.concurrent.Promise.timeout("Oops", 1 second)
Future.firstCompletedOf(Seq(externalRestServiceCall, timeoutFuture)).map {
  case first: List[Data] => Some(first)
  case _ => None
}

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    在我看来,最好不要考虑“提取”未来。

    如果您正在进行操作,只需使用Action.async(theWsFuture.map(wsRes => aPlayResult))

    您还可以在.async(...) 中将“非未来”结果与该未来混合:

    def myAction = Action async {
      for {
        a <- Future.successful(syncVal)
        b <- myFuture
      } yield Ok(somethingWithAB)
    }
    

    Play: How to implement action composition 上查看带有未来的动作组合。

    【讨论】:

    • 非常有用的回复,我听从了您的建议,并使用 Action.async 包装了我的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多