我有一个function(myFunc)在scala,它给了Future[Either[Throwable,T ]]。现在,我需要展开并从其中提取Either[Throwable,T ],并将其作为输入参数传递给另一个函数(anotherFunc)。
def myFunc(input: String): Future[Either[Throwable, HttpResponse]] = {
....
}
def anotherFunc(response: Either[Throwable, T]) # signature
anotherFunc(myFunc("some string"))通常我们使用map来转换一个Future,但这对我没有帮助
myFunc("some string").map { _ =>
anotherFunc(_)
}这会导致与我调用的块的return有关的问题。
发布于 2022-08-16 16:53:14
您无法打开Future的值,因为Future表示异步计算的结果,该结果可能可用,也可能不可用。默认情况下,期货和非阻塞,鼓励使用回调而不是典型的阻塞操作.
你可以做的是:
successfully.
map、flatMap、filter )以非阻塞的方式组合期货。
onComplete方法注册回调,如果您希望只在Future完成使用Await.result完成主线程时调用回调,则使用Await.result注册回调,尽管这是不鼓励的。如果要转换Future结果或将其与其他结果组合,则应选择前面提到的2种以前的非阻塞方式.这么说吧。这些是首选的办法:
def anotherFunc[T](response: Future[Either[Throwable, T]]) = {
response.onComplete {
case Failure(exception) => // process exception
case Success(value) => // process value
}
}
def anotherFunc2[T](response: Future[Either[Throwable, T]]) = {
response.map {
case Left(exception) => // process exception
case Right(value) => // process value
}
}然后你就可以:
anotherFunc(myFunc("some string"))
anotherFunc2(myFunc("some string"))编辑:如果您不能更改anotherFunc[T](response: Either[Throwable, T])的签名,那么只需:
myFunc("some string").map(anotherFunc)https://stackoverflow.com/questions/73376966
复制相似问题