Scala,在Future中更改变量值

时间:2016-12-15 04:01:02

标签: scala playframework

我的代码如下:

          val trxRequest: WSRequest = ws.url(route.transcationRoutes).withHeaders("Accept" -> "application/json")
          val futureResponse: Future[WSResponse] = trxRequest.post(Json.obj("trxtype" -> trxType, "trxvariable" -> trxVariable, "account" -> account.toJson))
          var responseStatus = 0 // I want to change this variable value
          futureResponse.map {
            response => {
              logkey = (LoginKeyUtils.getEncryptedKey(accountId))
              session.addSession(accountId -> logkey)

              responseStatus = response.status // I change it here

              println(responseStatus) // variable changed

              }

          }
          Ok(responseStatus +"") //But here back to 0 again

我想更改responseStatus值。它在map {}中的值已更改,但在外部地图时再次返回0。有什么不对?我是新手。

@Mikel,谢谢你,这是解决方案,

          val trxRequest: WSRequest = ws.url(route.transcationRoutes).withHeaders("Accept" -> "application/json")
          val futureResponse: Future[WSResponse] = trxRequest.post(Json.obj("trxtype" -> trxType, "trxvariable" -> trxVariable, "account" -> account.toJson))
          var responseStatus = 0
          //Need to retrieve as future
          val futureResult: Future[Any] = futureResponse.map {
            response => {
              logkey = (LoginKeyUtils.getEncryptedKey(accountId))
              session.addSession(accountId -> logkey)
              responseStatus = response.status;
              println(responseStatus)

            }
          }
          // wait for the result
          Await.result(futureResult, 5000 millis)
          Ok(responseStatus)

2 个答案:

答案 0 :(得分:1)

未来是异步执行的,因此在修改变量之前有很多机会执行Ok(responseStatus +“”)。

如果您想确定未来已经执行,可以在最后一行之前添加

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._    
Await.result(futureResponse, 5000 millis)

但在你的情况下,我猜你需要做的是将响应作为未来检索

val trxRequest: WSRequest = ws.url(route.transcationRoutes).withHeaders("Accept" -> "application/json")
val futureResponse: Future[WSResponse] = trxRequest.post(Json.obj("trxtype" -> trxType, "trxvariable" -> trxVariable, "account" -> account.toJson))
var responseStatus = 0 // I want to change this variable value
futureResponse.map {
    response => {
        logkey = (LoginKeyUtils.getEncryptedKey(accountId))
        session.addSession(accountId -> logkey)

        responseStatus = response.status // I change it here

        println(responseStatus) // variable changed
        Ok(responseStatus +"")
    }
}

答案 1 :(得分:0)

你应该避免在这里使用Await。

可以简单地

Action.async {
  ...
  futureResponse.map { r =>
    Ok(r.status + "")
  }
}

Action.asyncFuture[Result]作为http响应