return 来自 onComplete scala 的未来

return future from onComplete scala

关于 forComprehension 的 练习无法编译,因为 returns Unit 而不是 Future[User]

(任务是使用 DAO 读取并使用 2 个父节点创建新用户)

我正在尝试从 onComplete return Future[User] 但失败了(returns Unit)。

def unbornUsingForComp(fatherId: String, motherId: String): Future[User] = {

  val fatherUser: Future[Option[User]] = usersDao.read(fatherId)
  val motherUser: Future[Option[User]] = usersDao.read(motherId)

  val combinedLastName = for {
    r1 <- fatherUser
    r2 <- motherUser
  } yield (r1, r2)

  combinedLastName.onComplete {
    case Success(x) => {
      (x._1, x._2) match {
        case (Some(u1), Some(u2)) => usersDao.create(User("JustRandomId", "JustRandomFirstName", u1.lastName + " - " +u2.lastName))
        case _ => throw new Exception("One or more of the parents not Found")
      }
    }
    case Failure(_) => {
      throw new Exception("Exception raised inside the for comp.")
    }
  }
}

onComplete 设计 returns Unit 执行副作用然后丢弃

// Note that the returned value of `f` will be discarded.
def onComplete[U](f: Try[T] => U)(implicit executor: ExecutionContext): Unit

您可能在寻找类似的东西

combinedLastName
  .map { x => // do stuff with x }
  .recover { case e => // handle exception }