如何处理playframework控制器内的未来选项?

时间:2015-12-19 02:10:44

标签: scala playframework future

我的方法调用目前有以下签名:

val article:Future[Option[Article]] = articleService.getById(1)

我的控制器如下:

def show(id: Int) = Action.async { request =>
  articleService.getById(id).onSuccess {
    case articleOpt => {
      articleOpt.map{ 
         article => Ok("....")
      }
    }
  }
   Ok("fail")      
}

是否有更简洁的方法来处理Future[Option[Model]]

3 个答案:

答案 0 :(得分:4)

def show(id: Int) = Action.async { request =>
  articleService.getById(id).map {
    case Some(article) => Ok(article) 
    case None => Ok("...")
  }.recover{case ex => Ok("fail")}
}

更清洁的方式需要使用像scalaz ReaderT

这样的smth

答案 1 :(得分:1)

您也可以使用scalaz monad变换器OptionT:

import scalaz.OptionT

def show(id: Int) = Action.async { 
    OptionT(articleService.getById(id))
       .map(a => Ok(s"found: ${a.name}"))
       .getOrElse(NotFound("Not found"))
}

答案 2 :(得分:0)

也许是这样的

 def show(id: Int) = Action.async { request =>
  articleService.getById(id) map { op =>
        op match {
            case Some(acle) => Ok(s"found: ${acle.name}")
            case None => NotFound("Not found")                  
        }}
}