Slick 3使用flatMap方法提供DBIOAction组合。此外,我们可以在两个DBIOActions之间的后端进行一些计算。在大多数情况下,这样做很好,但是当计算结果像Future这样的monad时我该怎么做?有阻塞方式的代码:
val fooQuery = TableQuery[FooTable]
val barQuery = TableQuery[BarTable]
def requestService(content: Iterable[String]): Future[Iterable[Long]] = ???
def modify(ids: Iterable[Long], change: String) = {
val query = fooQuery.filter(_.id inSet ids).result.flatMap{ fooSeq =>
val content = fooSeq.map(_.contentField)
val requestServiceFuture = requestService(content)
val serviceResult = Await.result(requestServiceFuture, 1.minute)
barQuery.filter(_.id inSet serviceResult).delete //or other action
}
db.run(query.transactionally)
}
是否有办法异步执行此代码,没有Await?
答案 0 :(得分:6)
您可以使用DBIO
从Future
创建DBIOAction.from
,然后使用flatMap
val query = for {
fooSeq <- fooQuery.filter(_.id inSet ids).result
content = fooSeq.map(_.contentField)
serviceResult <- DBIOAction.from(requestService(content))
result <- barQuery.filter(_.id inSet serviceResult).delete
} yield result
db.run(query.transactionally)
http://slick.lightbend.com/doc/3.1.1/api/index.html#slick.dbio.DBIOAction $