Scala将异步调用与Future同步 [英] Scala Synchronising Asynchronous calls with Future

查看:329
本文介绍了Scala将异步调用与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)分别返回FutureSeq(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?

推荐答案

您可以参考所问的问题

Scala使用Future转换Seq

所以你得到了

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆