2017-01-31 22 views
0

裏面我已經異步播放Action,從datbase檢索數據,用油滑。和光滑,很明顯,使用Future,以免發生堵塞:製作獨立的油滑的查詢單玩動作

def show(id: Long) = Action.async { 
db.run(entities.filter(_.id === id).result.headOption).map { 
    case None => templateFor("NEW_OBJECT") 
    case Some(x) => Ok(x) 
} 
def templateFor(code: String): Future[Result] = { 
    db.run(templates.filter(_.code === code).result.headOption).map { 
    case None => InternalServerError("No template") 
    case Some(x) => Ok(x) 
    } 
} 

的問題是,調用templateFor()回報Future,所以整個Action回報Future[Future[Result]]它通過發揮不期望的。所以,我想擺脫嵌套Future。簡單的方法是完成Await,但我想避免不必要的阻塞。這將是很好,如果我將能夠採取由templateFor()函數產生Future[Result]並返回它從我的Action完好,從而取代外Future它。

+1

'flatMap'吧:) – ipoteka

+2

作爲@ipoteka說:https://cdn.meme.am/cache/instances/folder331/500x/67321331.jpg :) –

回答

2

您可以使用flatMap爲,

對於任何monandic strutcture如Future[T]flatMap需要T => SomeOtherMonad[K]類型的功能,適用於如果單子所有元素的功能,然後變平,他們給你Future[K]

def show(id: Long) = Action.async { 
    db.run(entities.filter(_.id === id).result.headOption).flatMap { 
    case None => templateFor("NEW_OBJECT") 
    case Some(x) => Future(Ok(x)) 
    } 

    def templateFor(code: String): Future[Result] = 
    db.run(templates.filter(_.code === code).result.headOption).map { 
     case None => InternalServerError("No template") 
     case Some(x) => Ok(x) 
    } 
}