Getting data out of a Future in Scala

喜欢而已 提交于 2019-12-19 04:16:07

问题


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]] = .... 

回答1:


There are multiple ways:

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

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)



回答2:


Blocking way (pauses your thread until you get the value back) using Await.result:

scala.concurrent.Await.result(futPersons, timeout)

Or, using a callback with onSuccess:

futPersons onSuccess {
    case persons => // do something with persons
}


来源:https://stackoverflow.com/questions/24028114/getting-data-out-of-a-future-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!