我最近读了曼努埃尔·伯恩哈特的新书《响应式Web应用程序》。在他的书中,他说Scala开发者永远不要使用
我想采纳他的建议,但是当我在Futures中使用for循环时,我很难避免使用
假设我有以下代码:
.get
来检索可选值。我想采纳他的建议,但是当我在Futures中使用for循环时,我很难避免使用
.get
。假设我有以下代码:
for {
avatarUrl <- avatarService.retrieve(email)
user <- accountService.save(Account(profiles = List(profile.copy(avatarUrl = avatarUrl)))
userId <- user.id
_ <- accountTokenService.save(AccountToken.create(userId, email))
} yield {
Logger.info("Foo bar")
}
通常情况下,我会使用AccountToken.create(user.id.get, email)
而不是AccountToken.create(userId, email)
。然而,当试图避免这种不良实践时,我会得到以下异常:
[error] found : Option[Nothing]
[error] required: scala.concurrent.Future[?]
[error] userId <- user.id
[error] ^
我该如何解决这个问题?
Option
和Future
组合的for-推导式 :( - irundaia.get
吗? - John DoeuserId <- user.id.map(concurrent.Future.successful(_) ).getOrElse(concurrent.Future.failed(new Exception(...)))
这样的代码可能会有所帮助。 - Victor Moroz