Play Framework 2 Scala WS Doing a Sync Request

2019-04-10 19:50发布

问题:

I am learning Scala. I used to use Play Framework 2 Java and trying to rewrite some of my previous work using and learning Scala.

I need to do a sync WS request and get Result Object from it somewhere in my code.

While I was back in Java, I used to do it like this:

WS.url("someurl").get().get(5000);

or with T Promise<T>.get(Long timeout) to be exact.

Since I switched to Scala, I am now using play.api.libs.ws and I rewrote code as:

val somefuture:Future[Response] = WS.url("someurl").get();

But I can't get Response from Future[Response] syncly! There is no .get() method on scala.

How can I get Response object from Future[Response] syncly?

回答1:

Use Await.result.

import scala.concurrent.duration._
import scala.concurrent.Await

....

val future: Future[Response] = ...
Await.result(future, 10 seconds): Response


回答2:

Use .map and return an asynchronous result. Check out this example:

https://github.com/TechEmpower/FrameworkBenchmarks/blob/master/play-scala/app/controllers/Application.scala#L44