2016-12-15 1 views
1

내부 변수 값을 변경합니다. 그것은지도 내부에서 값이 바뀌었지만 바깥 쪽지도에서는 ​​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

우리는 종종 작업 비동기 등을 위해 향후 구성/변환을 사용하는 HTTP 응답 등의 Future[Result] 소요 될 수 있습니다. 여기서'Await'을 사용하면 재생 메인 스레드를 차단합니다. '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

여기서 기다리는 것을 사용하지 않아도됩니다. 두 번째 발췌 문장에서는 기다리지 않고도 해결책을 볼 수 있습니다. – Mikel

0

여기서 기다려야합니다.

는 simplily

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

Action.async

관련 문제