我有一个这样的端点:嵌套的异步调用
POST /user/:id/addData
而且控制器功能如下:
def addData(id: Int) = Action.async { implicit request =>
// AsynC#1 - Make sure this user exists
usersDAO.get(id).map(user => {
is(user.isEmpty) {
BadRequest("That user doesn't exist")
} else {
val body = request.body.asJson.get.as[JsObject]
// Data processing here ...
// AsynC#2 - Insert some data from the POST body
(for {
foo <- fooDAO.insert(fooData)
bar <- barDAO.insert(barData)
} yield (foo, bar)).map {
case options => Ok("Data was added!")
}.recover { // <-------------------------- Compilation error here
case e => BadRequest(e)
}
}
})
}
我得到一个编译时错误:
type mismatch;
found : scala.concurrent.Future[play.api.mvc.Result]
required: play.api.mvc.Result
我相信这个错误是因为执行上下文在第一个异步调用(又名一个未来)中,所以,因为我正在输入另一个异步调用,就像我返回嵌套的期货一样。
这样做的正确方法是什么?如果可能的话,我想取消这些调用的嵌套(如Promises in Javascript)。