连锁2期货 - 计算一个并返回另一个

时间:2013-11-26 16:23:16

标签: multithreading scala future

我有一个Future和一个我希望在Future完成后执行的功能。并返回一个新的Future

我想创建一个函数,但我不能:

def chain(fut: Future[A], continueFun: Future[A] => B): Future[B] = future {
  fut onComplete {  case Success(x) => continueFun(x) }  // ops, Unit  
}    

为简单起见,我省略了onFailure

但是,onComplete,onSuccess和onFailure - 它们都返回UnitFuture[B]完成后如何返回Future[A]

2 个答案:

答案 0 :(得分:3)

根本问题有点复杂,但您可以flatMapmapjoin行为已经定义。

for {
   a <- someFuture
   b <- someOtherFuture
} yield {
   a + b // or whatever goes here
}

你甚至可以排序:

for {
   resultOfFuture <- someFuture
   nextResult <- getResult(resultOfFuture) // chaining them 
} yield {
   // etc
}


 def chain[A, B](fut: Future[A], continueFun: Future[A] => B): Future[B] = {
    for {
      a <- fut
    } yield {
      continueFun(fut)
    }
  }

答案 1 :(得分:1)

承诺可用于连锁期货。

def chain[A, B](fut: Future[A], continueFun: Future[A] => B): Future[B] = {

  val p = Promise[B]()  // A promise that will be completed after fut completes.

  fut onComplete {  case Success(x) => p success continueFun(fut) 
                    case Failure(ex) => p failure ex } 

  p.future // this future will be completed by the promise, which in turn will be completed by fut.

}