2013-11-26 25 views
1

我有一個Future和一個Future完成後我想要執行的功能。並返回一個新的Future連鎖2期貨 - 計算一個並返回另一個

我想創建一個函數這樣做,但我不能:

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 - 他們都返回Unit。一旦Future[A]完成後,如何返回Future[B]

+0

「continueFun」以「Future」爲參數很重要嗎?否則我認爲你可以簡單地做'futureA.map(continueFun)' – tehlexx

+0

@tehlexx,是的。 –

回答

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) 
    } 
    } 
+0

它是如何適用於我的'鏈'? –

+0

如果不是,你爲什麼給我那個答案? –

+0

我需要的解決方案不一定應該更簡單,它只應該適用於我的問題,而不是其他問題。 –

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. 

} 
+0

我也在思考諾言。 –

相關問題