ps0604 ps0604 - 4 months ago 27
Scala Question

Nested futures in Play for Scala does not compile

This

Action.async
method in Play for Scala should execute the second future only if the first future returns
1
, that's why they are nested. If the first future returns a result different than
1
then the second future should never be executed. But I'm getting the following compilation error in
f2.map
. Why is this error and how to fix it?


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


def index = Action.async { request =>

val f1 = Future {1}
f1.map {
access => if (access==1) {
val f2 = Future {2}
f2.map { // <-- compilation error
result => {
val json = JsObject(Seq(
"acc" -> JsNumber(access),
"ret" -> JsString("0")
))
Ok(json)
}
}
}
else {
val json = JsObject(Seq(
"acc" -> JsNumber(0),
"ret" -> JsString("0")
))
Future.successful(Ok(json))

}
}
}

Answer

You're basically there - just flatMap on f1 instead of map since you're creating another future.