【问题标题】:Play framework handle Future[Action]播放框架句柄 Future[Action]
【发布时间】:2017-10-06 20:13:22
【问题描述】:

喂!

我有 2 个控制器函数,它们返回一个动作。我有另一个控制器,可以在这些控制器之间进行选择,例如:

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?

【问题讨论】:

    标签: scala playframework


    【解决方案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")
          }
        }
      }
    }
    

    【讨论】:

    • 最后的那个 .run()... 我太接近了 :D 谢谢!
    • 未按预期工作需要更多验证...修改后我的一些测试失败:(
    猜你喜欢
    • 2020-06-22
    • 2015-08-30
    • 1970-01-01
    • 2012-11-30
    • 2013-02-20
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多