Usage of Scala Future in Playframework?

playframework-2.0, scala

Solution

You can use `Async`:

def index = Action{
    val myFunction:Future[Option[String]] = //
    Async{
      myFunction.map{
        case Some(x) => Ok(x)
        case None => InternalServerError
      }
    }
}

Basically you tell play that: Whenever `myFunction` is evaluated, return the result back to User. The trick here is to `map` on the `Future` content instead of using a callback, this lets you operate on the result.

The wonderful part is that it is still asynchronous. In the sense that the http request thread evaluation index will not get blocked.

Some documentation on it here.

Problem

When using Playframework, I am sometimes faced with this situation : ``` def myFunction:Future[String] = { // Do some stuff } myFunction.onComplete { case Success(myString) => // Du Stuff case Failure(error) => // Error handling } ``` But as stated in the Scala doc, `Future.onComplete` returns a Unit. How can I use those in Playframework when `Action` functions for example expect a `SimpleResult`? What are the best practices for handling Futures? EDIT : I should add, I am using Play-2.2.x branch which has traded the Play Future for the Scala Future.

Original source