您可能正在寻找
def combine[A](s: Seq[Future[Either[Error, Seq[A]]]]) = {
Future.sequence(s)
.map(x => {
x.foldRight(Right(Seq()): Either[Error, Seq[A]]) {
(e, acc) => for (xs <- acc.right; x <- e.right) yield x ++ xs
}
}
)
}
如果您希望仅在先前成功时才执行函数,请使用此
def combine[A](s: Seq[() => Future[Either[Error, Seq[A]]]]): Future[Either[Error, Seq[A]]] =
combine(Seq(), s)
def combine[A](acc: Seq[A], s: Seq[() => Future[Either[Error, Seq[A]]]]): Future[Either[Error, Seq[A]]] = s match {
case x +: Nil =>
val v = x.apply()
v.andThen {
case Success(Right(r)) => Success(Right(acc ++ r))
case Success(Left(l)) => Success(Left(l))
case Failure(f) => Failure(f)
}
case x +: xs =>
val v = x.apply()
v.andThen {
case Success(Right(r)) => combine(acc ++ r, xs)
case Success(Left(l)) => Success(Left(l))
case Failure(f) => Failure(f)
}
}