2016-11-14 41 views
2

Slick 3使用flatMap方法提供了DBIOAction組合。另外,我們可以在兩個DBIOAction之間的後端進行一些計算。這在大多數情況下都可以正常工作,但是當計算結果在未來的monad中時,我應該怎麼做?有代碼阻塞方式:如何在光滑3中使用Future內部的DBIOAction組合?

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) 
} 

有沒有辦法異步執行此代碼,沒有等待?

回答

3

您使用DBIOAction.from可以創建FutureDBIO,然後使用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 $

與其他DBIOs撰寫