访问斯卡拉期货返回的价值
我是scala期货的新手,并且对scala期货的回报价值有疑问.
I am a newbie to scala futures and I have a doubt regarding the return value of scala futures.
因此,一般来说,scala未来的语法是
So, generally syntax for a scala future is
def downloadPage(url: URL) = Future[List[Int]] {
}
我想知道如何从其他调用此方法的方法访问List[Int]
.
I want to know how to access the List[Int]
from some other method which calls this method.
换句话说,
val result = downloadPage("localhost")
那么,将List[Int]
淘汰的方法应该是什么?
then what should be the approach to get List[Int]
out of the future ?
我尝试使用map方法,但无法成功完成此操作.
I have tried using map method but not able to do this successfully.`
成功案例(listInt)=>我想返回listInt,但我不知道该怎么做.
The case of Success(listInt) => I want to return the listInt and I am not able to figure out how to do that.
最佳做法是您不返回该值.相反,您只是将未来(或用map
,flatMap
等转换的版本)传递给需要此值的每个人,他们可以添加自己的onComplete
.
The best practice is that you don't return the value. Instead you just pass the future (or a version transformed with map
, flatMap
, etc.) to everyone who needs this value and they can add their own onComplete
.
如果您确实需要返回它(例如,在实现传统方法时),那么您唯一可以做的就是阻止(例如,使用
If you really need to return it (e.g. when implementing a legacy method), then the only thing you can do is to block (e.g. with Await.result
) and you need to decide how long to await.