[英]How to unwrap a Future[Either[Throwable,T ]] to Either[Throwable,T]
I have a function
( myFunc
) in scala
that gives Future[Either[Throwable,T ]]
.我在
scala
中有一个function
( myFunc
),它给出Future[Either[Throwable,T ]]
。 Now I need to unwrap and get Either[Throwable,T ]
out of it and pass to as an input parameter to another function ( anotherFunc
).现在我需要打开并从中取出
Either[Throwable,T ]
并将其作为输入参数传递给另一个 function ( anotherFunc
)。
def myFunc(input: String): Future[Either[Throwable, HttpResponse]] = {
....
}
def anotherFunc(response: Either[Throwable, T]) # signature
anotherFunc(myFunc("some string"))
Normally we use map
to transform a Future
but thats not helping me here通常我们使用
map
来改变Future
,但这对我没有帮助
myFunc("some string").map { _ =>
anotherFunc(_)
}
This causes problem with the return
of the block from where I am calling.这会导致从我调用的块
return
问题。
You can't unwrap the value of a Future
because a Future
represents the result of an asynchronous computation that may or may not be available yet.您无法解开
Future
的值,因为Future
表示异步计算的结果,该结果可能还可能不可用。 By default, futures and non-blocking, encouraging the use of callbacks instead of typical blocking operations.默认情况下,futures 和非阻塞,鼓励使用回调而不是典型的阻塞操作。
What you can do is either:你可以做的是:
map
, flatMap
, filter
to compose futures in a non-blocking way.map
、 flatMap
、 filter
等组合器以非阻塞方式组合期货。onComplete
method, or foreach
if you want to call a callback only when the Future
completes successfully.onComplete
方法注册一个回调,如果您只想在Future
成功完成时调用回调,则使用foreach
。Await.result
, if this is absolutely necessary, although is discouraged.Await.result
阻塞主线程,如果这是绝对必要的,虽然不鼓励。 If you want to transform the Future
result or combine it with others, you should opt for the 2 previos non-blocking ways mentioned.Future
结果或将其与其他结果结合,您应该选择前面提到的 2 种非阻塞方式。 That being said.话虽如此。 These are the preferred approaches:
这些是首选方法:
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
}
}
Then you can do:然后你可以这样做:
anotherFunc(myFunc("some string"))
anotherFunc2(myFunc("some string"))
NOTE : If you can't change the signature of anotherFunc[T](response: Either[Throwable, T])
then just do:注意:如果您无法更改
anotherFunc[T](response: Either[Throwable, T])
的签名,那么只需执行以下操作:
myFunc("some string").map(anotherFunc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.