bsky
bsky

Reputation: 20222

Scala extract result from future

I am new to Scala, Play and using Futures. I have the following Play class which makes an API call and encapsulates the result in a Future.

How can I extract the result from the Future?

class WikiArticle(url : String) {

  var future : Future[WSResponse] = null

  def queryApi(): Unit = {
    val holder : WSRequest = WS.url(url)
    future = {
      holder.get()
    }
    future.onSuccess({
      //How do I extract the result here?
    });
  }

Upvotes: 2

Views: 1109

Answers (2)

Luong Ba Linh
Luong Ba Linh

Reputation: 802

future.onSuccess({
  case result => result.json
})

Upvotes: 0

Nyavro
Nyavro

Reputation: 8866

Try to avoid extracting result from future. For this you can chain future calls using for comprehensions:

val chainResult = for {
   result1 <- apiCallReturningFuture1;
   result2 <- apiCallReturningFuture2(result1)
} yield result2

In given example result1 is 'extracted' result of Future apiCallReturningFuture1. Once result1 is obtained it is passed to call to apiCallReturningFuture2 and 'unwrapped' to result2. Finally chainResult is a future wrapping result2 and it is still Future! Through your API you can chain and transform your futures without awaiting it's result

In the long run you may want to return result of the future in controller. In Play Framework you can do it by using Action.async:

def load(id:Long) = Action.async {
  repository.load(id)
    .map {
      case Some(x) => Ok(Json.toJson(x))
      case None => NotFound
    }
}

So I would not recommend await on futures except waiting in tests

Upvotes: 3

Related Questions