首页 > 解决方案 > 如何在 Scala 中结合 2 个期货

问题描述

我正在编写一个 CRUD rest api,但在服务层上合并 2 个期货时遇到了问题。

想法是将Entity插入db,然后通过id检索db生成的所有值。

我尝试了 Java 中的 andThen(),但它不能返回 Future[Entity],它说它仍然是 Future[Long]

class Service {
  def find(id: Long): Future[Option[Entry]] = db.run(repo.findEntry(id))

  //TODO Fails: Expression of type Future[Long] doesn't conform to expected type Future[Option[Entity]]
  def insert(): Future[Option[Entry]] = db.run(repo.insertEntry())
            .andThen { case Success(id) =>
                find(id)
            }
}

class Repository {
  def findEntry(id: Long): DBIO[Option[Entry]] =
    table.filter(_.id === id).result.headOption

  def insertEntry()(implicit ec: ExecutionContext): DBIO[Long] =
    table returning table.map(_.id) += Entry()
}

我觉得答案很简单,但就是找不到。

标签: scalafuture

解决方案


andThen是为了副作用,它仍然返回原始结果(第一个未来)。

你想要flatMap

 db.run(repo.insertEntry())
   .flatMap( id => find(id) )

flatMap还附带了一种特殊的语法,大多数人发现它更易读(在他们习惯之后),特别是如果它有更多的步骤:

 for {
   id <- db.run(repo.insertEntry())
   entry <- find(id)
 } yield entry

推荐阅读