簡體   English   中英

如何在Scala中結合2個期貨

[英]How to combine 2 Futures in Scala

我正在編寫一個CRUD Rest API,並在服務層上合並2個Futures時遇到問題。

這個想法是將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()
}

我覺得答案很簡單,但找不到。

andThen是副作用,它仍然返回(第一個Future的)原始結果。

您需要flatMap

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

flatMap還帶有一種特殊的語法,大多數人在習慣后會發現它們更具可讀性,尤其是在有更多步驟的情況下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM