本文介绍了期货/成功竞赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习期货,我想创建一个方法,将两个期货作为参数
( f
和 g
)并返回成功完成的第一个未来,否则返回 f
或 g
。
I'm learning futures, and I'm trying to create a method that, take two futures as parameter(f
and g
) and return the first future that was successfully completed, otherwise it returns f
or g
.
一些用例来说明我的方法的行为是:
Some use cases to illustrate the behaviour of my method are :
Future 1 | Future 2 | Result
Success First Success Second Future 1
Success First Failure Second Future 1
Success Second Success First Future 2
Success Second Failure First Future 1
Failure First Failure Second Future 2 (because we had a failure on Future 1, so try to see what is the result Future 2)
所以我创建了这个方法:
So I created this method :
def successRace(f: Future[T], g: Future[T]): Future[T] = {
val p1 = Promise[T]()
val p2 = Promise[T]()
val p3 = Promise[T]()
p1.completeWith(f)
p2.completeWith(g)
p3. ????
p3.future
}
现在,完成第一?
推荐答案
您要使用 tryCompleteWith
方法。
def successRace(f: Future[T], g: Future[T]): Future[T] = {
val p = Promise[T]()
p.tryCompleteWith(f)
p.tryCompleteWith(g)
p.future
}
这篇关于期货/成功竞赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!