从Scala的未来中获取数据 [英] Getting data out of a Future in Scala

查看:75
本文介绍了从Scala的未来中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Future[List[Person]] [1],我想从中获取List[Person].我该怎么办?

I've a Future[List[Person]][1] and I want to get the List[Person] from it. How can I do it ?

import scala.concurrent.Future
val futPersons : Future[List[Person]] = .... 

推荐答案

有多种方法:

futPersons.map { personList =>
  ....
}

此地图将返回另一个Future,由您从地图返回的内容组成.只有将来成功完成后,地图才会执行.如果您需要处理失败,可以使用onComplete

This map returns another Future composed with whatever you return from the map. The map will execute only if the future completes successfully. If you need to handle failure you can use onComplete

futPersons.onComplete {
  case Success(personList) => ...
  case Failure(exception)  =>  ... 
}

或者您可以等待将来的完成(这很困难):

Or you can wait for the future to complete (this is blocking):

val personList: List[Person] = Await.result(futPersons, 1 minutes)

这篇关于从Scala的未来中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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