Scala将异步调用与Future同步 [英] Scala Synchronising Asynchronous calls with Future
问题描述
我有一个方法可以执行几个数据库查找并执行一些逻辑.
I have a method that does a couple of database look up and performs some logic.
我从方法返回的MyType
对象如下:
The MyType
object that I return from the method is as follows:
case class MyResultType(typeId: Long, type1: Seq[Type1], type2: Seq[Type2])
方法定义如下:
def myMethod(typeId: Long, timeInterval: Interval) = async {
// 1. check if I can find an entity in the database for typeId
val myTypeOption = await(db.run(findMyTypeById(typeId))) // I'm getting the headOption on this result
if (myTypeOption.isDefined) {
val anotherDbLookUp = await(doSomeDBStuff) // Line A
// the interval gets split and assume that I get a List of thse intervals
val intervalList = splitInterval(interval)
// for each of the interval in the intervalList, I do database look up
val results: Seq[(Future[Seq[Type1], Future[Seq[Type2])] = for {
interval <- intervalList
} yield {
(getType1Entries(interval), getType2Entries(interval))
}
// best way to work with the results so that I can return MyResultType
}
else {
None
}
}
现在getType1Entries(interval)
和getType2Entries(interval)
分别返回Future
的Seq(Type1)
和Seq(Type2)
条目!
Now the getType1Entries(interval)
and getType2Entries(interval)
each returns a Future
of Seq(Type1)
and Seq(Type2)
entries!
我现在的问题是要从Future
中取出Seq(Type1)
和Seq(Type2)
并将其放入MyResultType
case类中?
My problem now is to get the Seq(Type1)
and Seq(Type2)
out of the Future
and stuff that into the MyResultType
case class?
推荐答案
您可以参考所问的问题
所以你得到了
val results2: Future[Seq([Iterable[Type1], [Iterable[Type2])] = ???
,然后在其上打电话等待,根本就没有Futures
,您可以做自己想做的事.
and then call await on it and you have no Futures
at all, you can do what you want.
我希望我正确理解了这个问题.
I hope I understood the question correctly.
哦,顺便说一句,您应该映射myTypeOption
而不是检查它是否已定义,如果没有定义,则返回None
Oh and by the way you should map myTypeOption
instead of checking if it's defined and returning None
if it's not
if (myTypeOption.isDefined) {
Some(x)
} else {
None
}
可以简单地替换为
myTypeOption.map { _ => // ignoring what actually was inside option
x // return whatever you want, without wrapping it in Some
}
这篇关于Scala将异步调用与Future同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!