scala - 在 Scala 中返回 future 之前记录其值

标签 scala

def returnFuture[A](x: A): Future[A] = {
      val xFuture = Future { x } // suppose an API call that returns a future
       xFuture.flatMap(x => {
            println(x) // logging the value of x
            xFuture
        })
    }

这就是我目前正在做的方式。提供更多背景信息:

当发出请求时,此函数在 API 内部被调用,并且我希望在返回请求中计算的值之前打印日志消息。这就是为什么,以下对我来说不是一个好的解决方案:

def returnFuture[A](x: A): Future[A] = {
      val xFuture = Future { x } // suppose an API call that returns a future
       xFuture.map(x => {
            println(x) // logging the value of x
        })
      xFuture
    }

最佳答案

日志记录是一种副作用,这意味着如果日志记录因任何原因失败(例如,调用 toString 抛出 NPE),您不希望操作失败。

Future#andThen非常适合这个用例。来自文档:

Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.

This method allows one to enforce that the callbacks are executed in a specified order.

Note that if one of the chained andThen callbacks throws an exception, that exception is not propagated to the subsequent andThen callbacks. Instead, the subsequent andThen callbacks are given the original value of this future.

你的例子变成:

def returnFuture[A](x: A): Future[A] = {
  Future { x } // suppose an API call that returns a future
    .andThen { case Success(v) => println(v) }
}

关于scala - 在 Scala 中返回 future 之前记录其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617405/

相关文章:

java - play.libs.WS 无法在 Play 框架中识别

scala - 将消息发送到Scala中的函数

c# - 为什么我们应该避免公共(public)方法?封装的好处

scala - 带有 Play2.4 和 scala 的 Google Guice 的循环依赖错误

java - Java 中最近的 FFTW 包装器

scala - "diverging implicit expansion"scalac 消息是什么意思?

python - 使用 JEP 将数据帧从 scala 传递到 python

scala - GSON JsonObject "Unsupported Operation Exception: null"getAsString

java - 将 Facebook 登录与 Play Framework 集成的库?

scala - 有什么方法可以使用反射在运行时访问 Scala 选项声明的类型吗?