Scala 完成后如何返回未来值?

Scala 完成后如何返回未来值?,scala,playframework,scalatest,Scala,Playframework,Scalatest,我编写了一个简单的方法,根据我在其中执行的服务调用返回Int列表 我的问题是,我拨打的服务电话返回的是一个有价值的未来,所以我认为我可以在未来完成并返回我想要的,但onComplete返回单位 这就是我希望它工作的方式: def getListOfInts(str: String): List[Int] = { myDaoService.findSomethingInDb(str).onComplete { case Success(res) =>

我编写了一个简单的方法,根据我在其中执行的服务调用返回Int列表

我的问题是,我拨打的服务电话返回的是一个有价值的未来,所以我认为我可以在未来完成并返回我想要的,但onComplete返回单位

这就是我希望它工作的方式:

  def getListOfInts(str: String): List[Int] = {
    myDaoService.findSomethingInDb(str).onComplete {
      case Success(res) =>
        res.map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
      case Failure(exception) => logger.error(s"finding in db has failed with exeption: ", exception)
    }
  }
什么是在未来完成时返回所需价值的正确方法

我通常知道它的
map/flatmap
,但这将使它在将来得到包装,我希望我的方法返回实际值,而不是值的未来


谢谢

等待。结果
是一条路要走,但不推荐。

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Await

def getListOfInts(str: String): List[Int] = {
  Await.result(myDaoService.findSomethingInDb(str), 10 seconds).map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
}
除非要使执行线程等待(阻塞)结果,否则不建议使用上述方法。上述代码不可缩放

推荐方式

def getListOfInts(str: String): Future[List[Int]] = 
myDaoService.findSomethingInDb(str).map { res =>
  res.map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
}

建议的方法是组合未来(使用map和flatmap将数据库调用的输出类型转换为所需的结果),然后最终等待获得最终转换的结果。

等待。结果是可行的方法,但不推荐。

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Await

def getListOfInts(str: String): List[Int] = {
  Await.result(myDaoService.findSomethingInDb(str), 10 seconds).map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
}
除非要使执行线程等待(阻塞)结果,否则不建议使用上述方法。上述代码不可缩放

推荐方式

def getListOfInts(str: String): Future[List[Int]] = 
myDaoService.findSomethingInDb(str).map { res =>
  res.map(line => line.amount.toInt*100).distinct.filter(num => num != 0).toList
}
建议的方法是组合未来(使用map和flatmap将数据库调用的输出类型转换为所需的结果),然后最终等待得到最终转换的结果。

onComplete、onSuccess和onFailure是您正在寻找的回调


onComplete、onSuccess和onFailure是您正在寻找的回调

您应该只在测试代码中使用wait.result()。确切地说,您可以接受这个答案。您有一个使用异步API的同步方法,因此您必须等待结果(这不是真正推荐的),或者必须使整个代码异步(依次返回未来)。@sheunis有时这是我们的事,例如,当您有两个库时,一个是异步的,另一个是同步的。因此,您必须使用Await(这很难看,但至少有一些版本的Await不忙于等待并阻止线程前进),或者您必须放弃同步(或异步)库,或者必须使同步库异步(这有时根本不可能)。您应该只在测试代码中使用Await.result(),你可以接受这个答案。您有一个使用异步API的同步方法,因此您必须等待结果(这不是真正推荐的),或者必须使整个代码异步(依次返回未来)。@sheunis有时这是我们的事,例如,当您有两个库时,一个是异步的,另一个是同步的。因此,您必须使用Await(这很难看,但至少有一些版本的Await不会忙着等待并阻止线程前进),或者您必须放弃同步(或异步)库,或者您必须使同步库异步(有时根本不可能).scala async可能会帮助您:scala async可能会帮助您: