2016-12-15 15 views
1

内の変数の値を変更します。値はmap {}内で変更されましたが、外側のマップでは再び0に戻りました。何か間違っていますか?私は初心者です。Scalaは、私は以下のコードを持って未来の

@Mikelは、将来を非同期で実行するので、変数が変更されている前に、[OK]を(responseStatus +は、「」)が実行されるチャンスがたくさんあるが、これは解決策である

  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

としてFuture[Result]を取るだろう。ここで 'Await'を使うと、メインのスレッドをブロックすることに注意してください。多くの 'Await'を使用する場合、メインスレッドプールがより多くのスレッドを持つように設定する必要がありました。 – jilen

答えて

1

をありがとう。

あなたが最後の行

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

ここで待つ必要はありませんが、2番目のスニペットでは、Awaitなしのソリューションを見ることができます – Mikel

0

ここではご使用をお避けください。

はsimplily

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

Action.async私たちはしばしば操作の非同期(async)などのために、将来の合成/変換を使用したHTTPレスポンス

関連する問題