等待另一个未来结束以返回函数 [英] Waiting for another future to end to return a function
问题描述
假设我有一个函数func1
,该函数需要返回带有两个整数的Future
.这两个值中的每一个都是由独立的期货返回的,就像这样:
Let's say I have a function func1
that needs to return a Future
with two integers. Each of the two values are returned by independent futures, like so:
def f1 = Future { 1 }
def f2 = Future { 2 }
def func1 : Future[(Int,Int)] = {
val future1 = f1
future1.map { result1 =>
result1 * 10
}
val future2 = f2
future2.map { result2 =>
result2 * 20
}
}
我需要future1
等待future2
结束(反之亦然),以将两个结果都作为(Int,Int)
返回.如何做到这一点?
I need future1
wait until future2
ends (or vice versa) to return both results as (Int,Int)
. How can this be accomplished?
推荐答案
这正是期货zip
方法的作用:
That's precisely what the zip
method on futures does:
val futurePair: Future[(Int, Int)] = future1.zip(future2)
请注意,如果您之前未实例化期货(例如,如果future1
和future2
是def
,而不是val
),则这将并行运行两个计算,而对于理解力(或flatMap
)将等待第一个成功,然后再开始第二个.
Note that if you haven't instantiated your futures before (say, if future1
and future2
are def
s, not val
s), this will run the two computations in parallel, while a for comprehension (or flatMap
) would wait for the first one to succeed before starting the second one.
这篇关于等待另一个未来结束以返回函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!