gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:28:19 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com