yang
yang

Reputation: 508

waiting for ws future response in play framework

I am trying to build a service that grab some pages from another web service and process the content and return results to users. I am using Play 2.2.3 Scala.

val aas = WS.url("http://localhost/").withRequestTimeout(1000).withQueryString(("mid", mid), ("t", txt)).get

val result = aas.map {
    response =>
      (response.json \ "status").asOpt[Int].map {
        st => status = st
      }
      (response.json \ "msg").asOpt[String].map {
        txt => msg = txt
      }
  }
  val rs1 = Await.result(result, 5 seconds)

  if (rs1.isDefined) {
      Ok("good")
  }

The problem is that the service will wait 5 seconds to return "good" even the WS request takes 100 ms. I also cannot set Await time to 100ms because the other web service I am requesting may take between 100ms to 1 second to respond.

My question is: is there a way to process and serve the results as soon as they are ready instead of wait a fixed amount of time?

Upvotes: 2

Views: 3197

Answers (1)

yang
yang

Reputation: 508

@wingedsubmariner already provided the answer. Since there is no code example, I will just post what it should be:

def wb = Action.async{ request =>
    val aas = WS.url("http://localhost/").withRequestTimeout(1000).get

    aas.map(response =>{
         Ok("responded")
    })
}

Now you don't need to wait until the WS to respond and then decide what to do. You can just tell play to do something when it responds.

Upvotes: 4

Related Questions