玩框架处理未来[动作]

时间:2017-10-06 08:58:36

标签: scala playframework

HY!

我有2个控制器功能,它们返回一个Action。我有另一个控制器,可以选择这些控制器,如:

def replace(i: Int, s:String): EssentialAction = ???
def asd: EssentialAction = {
    if(true){
      replace(5,"asd")
    } else {
      replace(6,"asd")
    }
}

但是当这个控制器使用db func时我会得到:

def asd: Future[EssentialAction] = {
  Future(true).map{ bool =>
    if(bool){
      replace(5,"asd")
    } else {
      replace(6,"asd")
    }
  }
}

但路由器无法处理Future [EssentialAction] :(

如何将Future [Action]重新编写为控制器内的Action?

1 个答案:

答案 0 :(得分:1)

此代码编译:

package controllers

import javax.inject._

import akka.stream.Materializer
import play.api.mvc._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class TestController @Inject()(cc: ControllerComponents)(implicit
  val mat: Materializer) extends AbstractController(cc) {

  def index = Action.async { request =>
    asd.flatMap(_.apply(request).run())
  }

  def replace(i: Int, s:String): EssentialAction = ???

  def asd: Future[EssentialAction] = {
    Future(true).map{ bool =>
      if(bool){
        replace(5,"asd")
      } else {
        replace(6,"asd")
      }
    }
  }
}