访问 Scala 期货返回的值 [英] Accessing value returned by scala futures

查看:19
本文介绍了访问 Scala 期货返回的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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.`

推荐答案

Success(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.

最佳做法是不要返回值.相反,您只需将未来(或使用 mapflatMap 等转换的版本)传递给需要此值的每个人,他们就可以添加自己的 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.

如果你真的需要返回它(例如在实现遗留方法时),那么你唯一能做的就是阻止(例如使用 Await.result) 并且您需要决定等待多长时间.

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.

这篇关于访问 Scala 期货返回的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆