给定一个Future[T],我可以写一个onComplete回调函数返回T



我有这个方法:

def findById(id: String): Customer = {
     (new CustomerDaoEs).retrieve(Id[Customer](id)) onComplete {
      case Success(customer) => customer
      case Failure(t) => {
        throw new InvalidIdException(id.toString, "customer")
      }
    }
  }

当然,问题是这里返回的是Unit而不是Customer…所以基本上onComplete的行为不像模式匹配。

是否有任何方法来保持返回客户(或选项[客户]),并使这个工作很好(我的意思是保持这个onComplete干净的结构)?

您可以使用recover方法更改exception:

def findById(id: String): Future[Customer] = {
  (new CustomerDaoEs).retrieve(Id[Customer](id)).recover{ case _ => throw new InvalidIdException(id.toString, "customer") }
}

那么你可以这样使用你的方法:

val customer = Await.result(findById("cust_id"), 5.seconds)

或者您可以将exception替换为None:

def findById(id: String): Future[Option[Customer]] = {
  (new CustomerDaoEs).
    retrieve(Id[Customer](id)).
    map{ Some(_) }.
    recover{ case _ => None }
}

主要问题是onComplete是非阻塞的。因此,您将不得不使用Await并返回结果。

def findById(id: String): Customer = 
  Await.result(
    awaitable = (new CustomerDaoEs).retrieve(Id[Customer](id))),
    atMost = 10.seconds
  )

然而,我宁愿建议保持代码非阻塞,并使findById返回Future[Customer]

相关内容

最新更新