scala - 如何在 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()
}
我觉得答案很简单,但就是找不到。
解决方案
andThen
是为了副作用,它仍然返回原始结果(第一个未来)。
你想要flatMap
。
db.run(repo.insertEntry())
.flatMap( id => find(id) )
flatMap
还附带了一种特殊的语法,大多数人发现它更易读(在他们习惯之后),特别是如果它有更多的步骤:
for {
id <- db.run(repo.insertEntry())
entry <- find(id)
} yield entry
推荐阅读
- r - 使用 R 在 GLM 回归中运行所有可能的交互
- angular - 当我是 Observable.interval 时如何允许函数 sortbydate()
- vba - 如何选择过滤器位置而不是它的实际名称?
- node.js - Mongoose 5.0.15 / MongoDB 3.6.4 转换为数组失败的值 [NaN,NaN]
- ios - iOS 上的 GeoFire 与 Firebase 5
- c# - 按钮单击事件后 DataTable 不渲染 Gridview
- python - 在给定收敛标准的情况下实现主持人提前停止
- windows - 没有名为“encondings”的模块
- r - asMethod(object) 中的错误,使用 Apriori 离散列第一个错误
- python - 无法使用 smtplib 接收邮件,因为收件人被添加到密件抄送列表中