尝试返回Future [Result]时在playframework中获取控制器返回类型错误

时间:2017-04-13 13:09:54

标签: scala playframework playframework-2.0 concurrent.futures

我的控制器流程非常复杂,这就是使用单词的方式:

- get the request 

- translate it to my model
  case it succeed: 
      insert some record to my db
         case it succeed:
            perform some api call
               case it succeed:
                  match its returned value 
               case failed:
         recover with proper result
         case failed:
            recover with proper result
  case failed:
     recover with proper result

但在我的代码中我得到一些错误,某些地方我没有正确地返回结果的未来......

错误:

  

类型单位的表达式不符合预期的类型   未来[结果]

这是代码:

def myApiMethod ...

    val requestAsModel = request.body.extractOpt[MyModel]

    requestAsModel match {
      case Some(req) =>
        // returning Future
        dbService.insert.onComplete {
          case Success(x) =>
            myApiService.doSomething(req).map {
              case good: GoodRes => Ok(Extraction.decompose(good))
              case bad: BadRes => BadRequest(Extraction.decompose(bad))
            } recover {
              case ex =>
                InternalServerError
            }
          case Failure(ex) => Future {InternalServerError}
        }
      case None =>
        Future.successful(BadRequest("not a good body content"))
    }
}

所以你在这里看到了问题?

并且以这种方式编写控制器似乎是一个好习惯吗?

感谢

1 个答案:

答案 0 :(得分:0)

Future onComplete 方法返回单元documentation。 您需要使用 flatMap 调用替换 onComplete ,以便能够将结果转换为Future [Result]:

    dbService.insert.flatMap{
        case Success(x) => 
              myApiService.doSomething(req).map {
                  case good: GoodRes => Ok(Extraction.decompose(good))
                  case bad: BadRes => BadRequest(Extraction.decompose(bad))
             } recover {
              case ex =>
                InternalServerError
            }
        case Failure(ex) => Future {InternalServerError}
    }

我建议您阅读这篇文章Scala Futures guide。特别是关于组成期货的一部分。