Scala:忽略失败的期货,将[未来]列出到[期货]


116

我正在寻找一种将任意长度的Future列表转换为List的Future的方法。我正在使用Playframework,所以最终,我真正想要的是一个Future[Result],但是为了简化起见,我们可以说Future[List[Int]]通常的做法是使用它,Future.sequence(...)但是有一点曲折...通常我给出的列表有大约10到20种期货,而且其中一种期货失败(他们正在提出外部Web服务请求)并不罕见。如果希望其中一个失败,则不必重试所有这些,而是​​希望能够找到成功的并返回它们。

例如,执行以下操作无效

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) :: 
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure

除了希望获得唯一的例外,我还希望能够将1和3从那里拉出来。我尝试使用Future.fold,但显然只是Future.sequence在后台调用。

在此先感谢您的帮助!

Answers:


146

诀窍是首先确保所有期货都没有失败。 .recover是您的朋友,您可以将其与map将所有Future[T]结果转换为Future[Try[T]]]实例,将所有这些都肯定是成功的未来。

注意:您也可以在此处使用OptionEither,但是Try如果您特别想捕获异常,这是最干净的方法

def futureToFutureTry[T](f: Future[T]): Future[Try[T]] =
  f.map(Success(_)).recover { case x => Failure(x)}

val listOfFutures = ...
val listOfFutureTrys = listOfFutures.map(futureToFutureTry(_))

然后Future.sequence像以前一样使用,给您一个Future[List[Try[T]]]

val futureListOfTrys = Future.sequence(listOfFutureTrys)

然后过滤:

val futureListOfSuccesses = futureListOfTrys.map(_.filter(_.isSuccess))

如果需要,您甚至可以排除特定的故障:

val futureListOfFailures = futureListOfTrys.map(_.filter(_.isFailure))

谢谢!.recover确实是我所缺少的。
2014年

20
您可以使用_.collect{ case Success(x) => x}代替_.filter(_.isSuccess)来摆脱的Try类型futureListOfSuccesses
senia 2014年

43
在scala 2010 .recover(x => Failure(x))中无效,请.recover({case e => Failure(e)})改用
FGRibreau

我认为您缺少了未来的包装器:def futureToFutureOfTry [A](f:Future [A]):Future [Try [A]] = {val p = Promise [Try [A]]()f.map {a => p.success(scala.util.Success(a))} .recover {case x:Throwable => p.success(Failure(x))} p.future}
Dario

不是。我正在将Future映射到另一个Future,不需要介入的Promise将会很浪费
Kevin Wright

12

Scala 2.12的改进之处在于Future.transform,它可以用更少的代码来修饰自己。

val futures = Seq(Future{1},Future{throw new Exception})

// instead of `map` and `recover`, use `transform`
val seq = Future.sequence(futures.map(_.transform(Success(_)))) 

val successes = seq.map(_.collect{case Success(x)=>x})
successes
//res1: Future[Seq[Int]] = Future(Success(List(1)))

val failures = seq.map(_.collect{case Failure(x)=>x})
failures
//res2: Future[Seq[Throwable]] = Future(Success(List(java.lang.Exception)))

11

我尝试了Kevin的答案,但在我的Scala版本(2.11.5)上遇到了故障。

implicit class FutureCompanionOps(val f: Future.type) extends AnyVal {

    /** Given a list of futures `fs`, returns the future holding the list of Try's of the futures from `fs`.
      * The returned future is completed only once all of the futures in `fs` have been completed.
      */
    def allAsTrys[T](fItems: /* future items */ List[Future[T]]): Future[List[Try[T]]] = {
      val listOfFutureTrys: List[Future[Try[T]]] = fItems.map(futureToFutureTry)
      Future.sequence(listOfFutureTrys)
    }

    def futureToFutureTry[T](f: Future[T]): Future[Try[T]] = {
      f.map(Success(_)) .recover({case x => Failure(x)})
    }

    def allFailedAsTrys[T](fItems: /* future items */ List[Future[T]]): Future[List[Try[T]]] = {
      allAsTrys(fItems).map(_.filter(_.isFailure))
    }

    def allSucceededAsTrys[T](fItems: /* future items */ List[Future[T]]): Future[List[Try[T]]] = {
      allAsTrys(fItems).map(_.filter(_.isSuccess))
    }
}


// Tests... 



  // allAsTrys tests
  //
  test("futureToFutureTry returns Success if no exception") {
    val future =  Future.futureToFutureTry(Future{"mouse"})
    Thread.sleep(0, 100)
    val futureValue = future.value
    assert(futureValue == Some(Success(Success("mouse"))))
  }
  test("futureToFutureTry returns Failure if exception thrown") {
    val future =  Future.futureToFutureTry(Future{throw new IllegalStateException("bad news")})
    Thread.sleep(5)            // need to sleep a LOT longer to get Exception from failure case... interesting.....
    val futureValue = future.value

    assertResult(true) {
      futureValue match {
        case Some(Success(Failure(error: IllegalStateException)))  => true
      }
    }
  }
  test("Future.allAsTrys returns Nil given Nil list as input") {
    val future =  Future.allAsTrys(Nil)
    assert ( Await.result(future, 100 nanosecond).isEmpty )
  }
  test("Future.allAsTrys returns successful item even if preceded by failing item") {
    val future1 =  Future{throw new IllegalStateException("bad news")}
    var future2 = Future{"dog"}

    val futureListOfTrys =  Future.allAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys, 10 milli)
    System.out.println("successItem:" + listOfTrys);

    assert(listOfTrys(0).failed.get.getMessage.contains("bad news"))
    assert(listOfTrys(1) == Success("dog"))
  }
  test("Future.allAsTrys returns successful item even if followed by failing item") {
    var future1 = Future{"dog"}
    val future2 =  Future{throw new IllegalStateException("bad news")}

    val futureListOfTrys =  Future.allAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys,  10 milli)
    System.out.println("successItem:" + listOfTrys);

    assert(listOfTrys(1).failed.get.getMessage.contains("bad news"))
    assert(listOfTrys(0) == Success("dog"))
  }
  test("Future.allFailedAsTrys returns the failed item and only that item") {
    var future1 = Future{"dog"}
    val future2 =  Future{throw new IllegalStateException("bad news")}

    val futureListOfTrys =  Future.allFailedAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys,  10 milli)
    assert(listOfTrys(0).failed.get.getMessage.contains("bad news"))
    assert(listOfTrys.size == 1)
  }
  test("Future.allSucceededAsTrys returns the succeeded item and only that item") {
    var future1 = Future{"dog"}
    val future2 =  Future{throw new IllegalStateException("bad news")}

    val futureListOfTrys =  Future.allSucceededAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys,  10 milli)
    assert(listOfTrys(0) == Success("dog"))
    assert(listOfTrys.size == 1)
  }

7

我刚遇到这个问题,并提供另一种解决方案:

def allSuccessful[A, M[X] <: TraversableOnce[X]](in: M[Future[A]])
                                                (implicit cbf: CanBuildFrom[M[Future[A]], A, M[A]], 
                                                 executor: ExecutionContext): Future[M[A]] = {
    in.foldLeft(Future.successful(cbf(in))) {
      (fr, fa)(for (r ← fr; a ← fa) yield r += a) fallbackTo fr
    } map (_.result())
}

这里的想法是,在折叠中,您正在等待列表中的下一个元素完成(使用for-comprehension语法),如果下一个失败,您将退回到已经拥有的位置。


我不喜欢这个名字,但是我喜欢它的完成方式,直接从序列impl
crak

1

您可以使用option轻松包装将来的结果,然后将列表展平:

def futureToFutureOption[T](f: Future[T]): Future[Option[T]] =
    f.map(Some(_)).recover {
      case e => None
    }
val listOfFutureOptions = listOfFutures.map(futureToFutureOption(_))

val futureListOfOptions = Future.sequence(listOfFutureOptions)

val futureListOfSuccesses = futureListOfOptions.flatten

万一其他人在第一个函数中遇到Some错误,可以像这样重写第一个函数以防止编译器错误:def futureToFutureOption [T](f:Future [T]):Future [Option [T]] = f.map(Option(_))。recover {case e => None}
Zee18年

0

您还可以在不同的列表中收集成功和失败的结果:

def safeSequence[A](futures: List[Future[A]]): Future[(List[Throwable], List[A])] = {
  futures.foldLeft(Future.successful((List.empty[Throwable], List.empty[A]))) { (flist, future) =>
    flist.flatMap { case (elist, alist) =>
      future
        .map { success => (elist, alist :+ success) }
        .recover { case error: Throwable => (elist :+ error, alist) }
    }
  }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.