2014-08-28 47 views
0

我必須從我的Scala Play框架應用程序調用外部REST服務。使用WS API我得到一個未來,並不確定哪個是從這個未來「提取」價值的最佳方式。這裏是我的代碼:玩框架 - 使用WS API

val externalRestServiceCall: Future[List[Data]] = WS.clientUrl(dataSourceProperties.url).get().map { 
    response => response.json.as[List[Data]] 
} 

,這是我目前的做法,雖然返回一個未來:

val timeoutFuture = play.api.libs.concurrent.Promise.timeout("Oops", 1 second) 
Future.firstCompletedOf(Seq(externalRestServiceCall, timeoutFuture)).map { 
    case first: List[Data] => Some(first) 
    case _ => None 
} 

回答

1

在我看來,最好不要想「提取」的未來。

如果您正在採取行動,只需使用Action.async(theWsFuture.map(wsRes => aPlayResult))即可。

你也可以混合「非未來」裏面.async(...)這個未來的結果是:未來在Play: How to implement action composition

def myAction = Action async { 
    for { 
    a <- Future.successful(syncVal) 
    b <- myFuture 
    } yield Ok(somethingWithAB) 
} 

見行動組成。

+0

非常有用的回覆,我遵循了你的建議,並用Action.async封裝了我的動作。 – ardlema 2014-08-30 18:15:04