Rah*_*ogi 1 scala playframework playframework-2.0
我必须同时执行大约10到15个查询.在哪里,这些查询相互依赖,我将这些查询放在一起.否则,每个查询我有一个未来.现在我只想在执行所有查询时,然后在包含未来的函数中指示成功或失败的响应.
val f1 = future{SQL("insert into user_general_info (user_id, userFName, userLName, displayAs)" +
"values(" + userId + ",'" + form.fname + "','" + form.lname + "','1')").executeInsert();
}
val f2 = future {
SQL("insert into personal('" + userId + "',1,1,0,0,1,'ALL',0,'E')").executeInsert();
}
/*
and so on...upto about f1 to f14 futures...
*/
Run Code Online (Sandbox Code Playgroud)
现在我做的是:
val job = for {
a1 <- f1
a2 <- f2
a3 <- f3
a4 <- f4
a5 <- f5
a6 <- f6
a7 <- f7
a8 <- f8
a9 <- f9
a10 <- f10
a11 <- f11
a12 <- f12
a13 <- f13
a14 <- f14
} yield ()
var res: Boolean = false
job.onSuccess {
case result => res = true
}
if(res)
List((1, userId, username)) //1 means success
else
List((-2, userId, username)) //-2 means failure
Run Code Online (Sandbox Code Playgroud)
问题是所有查询都没有运行,响应List((-2,userId,username))是基于变量res发送的.但是List((1,userId,username))当所有的期货都完成时应该已经退还了.救命...
您可以使用Futures.sequence在单个未来转换期货列表.
Composing Futures的代码示例:
// oddActor returns odd numbers sequentially from 1 as a List[Future[Int]]
val listOfFutures = List.fill(100)(akka.pattern.ask(oddActor, GetNext).mapTo[Int])
// now we have a Future[List[Int]]
val futureList = Future.sequence(listOfFutures)
// Find the sum of the odd numbers
val oddSum = futureList.map(_.sum)
oddSum foreach println
Run Code Online (Sandbox Code Playgroud)
在旁注中,我建议返回一个Option表示成功或失败的例子
if(res) Some(List(userId, userName))
else None
Run Code Online (Sandbox Code Playgroud)