Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Play 2.1.1 async requests and futures

The code below doesn't compile and I don't know how to fix it.

def doAsync(n: Int) = Action {
  import scala.concurrent.ExecutionContext.Implicits.global

  Async {
    val f1 = Future.successful(n)

    f1.map(x => x match {
      case 10 => Ok("first")
      case _ => {
        val f2 = Future.successful(n)
        f2.map(y => Ok("second"))
      }
    })
  }
}

The line f2.map(y => Ok("second")) produces the compile error:

type mismatch; found: scala.concurrent.Future[play.api.mvc.SimpleResult[String]] required: play.api.mvc.Result

The core "business logic" is: f2 only must run if n is not 10.

like image 526
user2514593 Avatar asked Jun 24 '13 00:06

user2514593


1 Answers

f1 is going to be a future of a result.

You're returning a result for case 10, and a a future of a result otherwise. You need to put the result into the same terms. Try:

f1 flatMap {x => x match {
  case 10 => Future.successful(Ok("first"))
  case _ => {
    val f2 = Future.successful(n)
    f2.map(y => Ok("second"))
  }
}
like image 142
Christopher Hunt Avatar answered Nov 14 '22 10:11

Christopher Hunt