Playframework:找不到类型不匹配scala.concurrent.Future [play.api.mvc.Result] required:play.api.mvc.Result

时间:2016-06-13 07:58:09

标签: scala playframework-2.5

我在PlayFramework的控制器中有以下代码:

  def auth = Action.async(parse.json) { request =>
    {

      val authRequest = request.body.validate[AuthRequest]
      authRequest.fold(
        errors => Future(BadRequest),
        auth => {
          credentialsManager.checkEmailPassword(auth.email, auth.password).map {

            case Some(credential: Credentials) => {

              sessionManager.createSession(credential.authAccountId).map { //Throws an error
                case Some(authResponse: AuthResponse) => Ok(Json.toJson(authResponse))
                case None => InternalServerError

              }

            }

            case (None) => Unauthorized
          }

        })
    }
  }

我在上面有错误评论的行中收到以下错误:

Type Mismatch:
[error]  found   : scala.concurrent.Future[play.api.mvc.Result]
[error]  required: play.api.mvc.Result
[error]               sessionManager.createSession(credential.authAccountId).map {

createSession调用返回Future[Option[Object]],但我无法弄清楚如何解决这个问题。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

简短回答: 将第.map行中的.flatMap更改为credentialsManager.checkEmailPassword(auth.email, auth.password).map,将case (None) => Unauthorized更改为case None => Future(Unauthorized)

说明:

credentialsManager.checkEmailPassword(auth.email, auth.password)返回Future[Option[Credentials]],其上的映射将始终返回Future,其中sessionManager.createSession(credential.authAccountId)也会返回Future因此,credentialsManager.checkEmailPassword(auth.email, auth.password)的最终结果{1}} Future[Future[something]]为了避免出现这种情况,您可以flatten代替它map它可以通过flatmap

一步完成

答案 1 :(得分:1)

不确定,但这应该有效:

def auth = Action.async(parse.json) { request =>
{

  val authRequest = request.body.validate[AuthRequest]
  authRequest.fold(
    errors => Future(BadRequest),
    auth => {
      credentialsManager.checkEmailPassword(auth.email, auth.password).flatMap { //flatMap

        case Some(credential: Credentials) => {

          sessionManager.createSession(credential.authAccountId).map {
            case Some(authResponse: AuthResponse) => Ok(Json.toJson(authResponse))
            case None => InternalServerError

          }

        }

        case None => Future(Unauthorized) //Wrap it
      }

    })
}

}

这是对代码的简化,并附有一些注释。我希望这足以抓住这个想法:

 Future(Option("validCredentials")).flatMap {
   case Some(credential) => Future("OK")
   case None => Future("Unauthorized")
 }
 //Future[Option[String]].flatMap(Option[String] => Future[String])
 //Future[A].flatMap(A => Future[B]) //where A =:= Option[String] and B =:= String

答案 2 :(得分:0)

未来(“未经授权”)这是无效的请使用Future.successful(Ok(“OK”)) Future.successful(错误请求(未授权))