我對Action.async的預期結果有點混淆。這裏的用例是:從前端,我收到一個JSON來驗證(一個Foo),我發送這個數據調用另一個Web服務,然後提取並驗證我想驗證的JSON(Bar case類)。問題是,當我返回一個結果,我有以下錯誤:玩Scala - 混淆Action.async的結果類型
type mismatch;
found : Object
required: scala.concurrent.Future[play.api.mvc.Result]
這裏我的代碼:
case class Foo(id : String)
case class Bar(id : String)
def create() = {
Action.async(parse.json) { request =>
val sessionTokenOpt : Option[String] = request.headers.get("sessionToken")
val sessionToken : String = "Bearer " + (sessionTokenOpt match {
case None => throw new NoSessionTokenFound
case Some(session) => session
})
val user = ""
val structureId : Option[String] = request.headers.get("structureId")
if (sessionToken.isEmpty) {
Future.successful(BadRequest("no token"))
} else {
val url = config.getString("createURL").getOrElse("")
request.body.validate[Foo].map {
f =>
Logger.debug("sessionToken = " + sessionToken)
Logger.debug(f.toString)
val data = Json.toJson(f)
val holder = WS.url(url)
val complexHolder =
holder.withHeaders(("Content-type","application/json"),("Authorization",(sessionToken)))
Logger.debug("url = " + url)
Logger.debug(complexHolder.headers.toString)
Logger.debug((Json.prettyPrint(data)))
val futureResponse = complexHolder.put(data)
futureResponse.map { response =>
if(response.status == 200) {
response.json.validate[Bar].map {
b =>
Future.successful(Ok(Json.toJson(b)))
}.recoverTotal { e : JsError =>
Future.successful(BadRequest("The JSON in the body is not valid."))
}
} else {
Logger.debug("status from apex " + response.status)
Future.successful(BadRequest("alo"))
}
}
Await.result(futureResponse,5.seconds)
}.recoverTotal { e : JsError =>
Future.successful(BadRequest("The JSON in the body is not valid."))
}
}
}
}
什麼是錯誤的,我的功能?
卸下的await讓我的另一個錯誤:'類型不匹配; 找到的:scala.concurrent.Future [對象] 必需:scala.concurrent.Future [play.api.mvc.Result]'。可以肯定的是,從類型系統中,爲什麼我的函數(沒有等待)沒有很好地輸入? – alifirat
'futureResponse'的類型是什麼?也許你在那裏嵌套了Futures,並且需要一些'flatMap'。最後,你需要結束'Future [結果]'。 – Thilo
futureResult的類型:'scala.concurrent.Future [play.api.libs.ws。WSResponse]' – alifirat