2016-12-15 57 views
1

我有下面的代码:斯卡拉,改变变量值内未来

  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值。它在地图{}内更改了值,但在外部地图时再次回到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) 
+0

我们经常使用未来组合物/转化为这样的异步操作。如果你在这里使用'Await',注意会阻止播放主线程。如果使用大量的“等待”,则必须将主线程池配置为拥有更多线程。 – jilen

回答

1

未来是异步执行的,所以有一些变量已被修改之前好(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 +"") 
    } 
} 
+0

非常感谢,重点是**未来是异步执行**。正确的,我需要检索响应作为未来,并等待结果。是工作。谢谢 –

+0

你并不需要在这里使用await,在第二个片段中你可以看到没有等待的解决方案 – Mikel

0

你应该避免在这里使用等待。

可能simplily是

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

Action.async需要一个Future[Result]作为HTTP响应