【问题标题】:scala: playframework controller action execution sequence with futurescala:带有未来的playframework控制器动作执行序列
【发布时间】:2018-10-24 23:22:22
【问题描述】:

我的播放框架 API 服务器有问题。我需要在后台运行一些处理,返回带有结果的Future,然后将结果写入响应。但是,请求线程在我的 Future 完成之前全力以赴并返回。这是代码...

 def requestAction(): Action[AnyContent] = Action.async { implicit request =>
    var fResult: Future[String] = Future { "initial value" }
    try {
       fResult = doSomethingAsyncAndGetResponseString(); // return "great, everything is done"
    }
    catch {
       case t: Throwable {
           fResult = Future { "failed" }
       }
    }
    // done, return response, but the problem is, this is executed first because doSomethingAsyncAndGetResponseString() is still executing and returns later
    fResult.map( res => {
        // problem here, because I get "initial value" which is not what I want
        Ok(res)
    }
}

没有Async.await,有没有办法让“很棒,一切都完成”或“失败”?我一直在我的 API 服务器中使用这种格式,但今天它坏了,因为在我编写的一个新 API 中,doSomethingAsyncAndGetResponseString 有点长。我没想到,所以我对结构的理解一定有问题。

提前致谢!

【问题讨论】:

    标签: scala playframework future


    【解决方案1】:

    您正在尝试使用Scala 编写类似Java 的代码。

    你做错了。阅读Futures 以及如何使用它们。

    这里是tutorial

    Futures 可以使用mapflatMap 结构组成。 recoverrecoverWith 将允许用户访问计算管道中发生的异常

    你必须这样做,如下所示

    def requestAction(): Action[AnyContent] = Action.async { implicit request =>
        Future { "initial value" }.flatMap { _ =>
          doSomethingAsyncAndGetResponseString() // returns Future
        }.map { res =>
          Ok(res)
        }.recover { case th =>
          Ok(th.getMessage)
        }
    }
    

    处理异常并从异常中恢复

    异常处理内置于Future

    recover 提供对异常的访问权限,并帮助用户在异常情况下提供替代的成功值。

    recoverWith 提供对异常的访问权限,还帮助用户提供/链接替代Future 计算,可以成功或失败。

    Future {
     throw new Exception("foo exception")
    }.recover {
      case th => println(s"msg: ${th.getMessage}")
    }
    

    【讨论】:

    • 谢谢!这是一个有趣的阅读!但是关于您的示例的一个快速问题,如果我以这种方式包装它,那么我不能catch 任何可能出现的错误并“正确”处理它?打印“失败”案例?
    • @Zennichimaro recoverrecoverWith 将有助于捕获异常
    • @Zennichimaro 添加了有关异常恢复的更多信息
    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 2018-03-18
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2012-05-31
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多