有没有办法转换一个
Either[A, Future[B]]
到一个
Future[Either[A, B]]
我想到了类似
Future.sequence
方法的东西,该方法可以将List[Future]
转换为Future[List]
最佳答案
不确定是否有开箱即用的解决方案,这就是我想出的解决方案:
def foldEitherOfFuture[A, B](e: Either[A, Future[B]]): Future[Either[A, B]] =
e match {
case Left(s) => Future.successful(Left(s))
case Right(f) => f.map(Right(_))
}
除了从
Future
捕获最终异常之外,您还可以添加recover
并将其映射到Left
:case Right(f) => f.map(Right(_)).recover { case _ => Left(/** some error*/) }
关于scala - [A,Future [B]]到Future [E [[A,B]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875230/