你会如何使用Scala的异步超时多个异步请求?

时间:2014-04-04 21:44:56

标签: c# scala asynchronous go

我不了解Scala,但我很好奇它的异步功能(类似于C#' s)。您如何将此代码转换为Scala异步?

http://talks.golang.org/2012/concurrency.slide#47

c := make(chan Result)
go func() { c <- Web(query) } ()
go func() { c <- Image(query) } ()
go func() { c <- Video(query) } ()

timeout := time.After(80 * time.Millisecond)
for i := 0; i < 3; i++ {
    select {
    case result := <-c:
        results = append(results, result)
    case <-timeout:
        fmt.Println("timed out")
        return
    }
}
return

1 个答案:

答案 0 :(得分:0)

这是一个如何完成的草图(未经测试;我没有声称这是最好的解决方案):

// I assume that the Web/Image/Video functions return instances of Future[Result]
val f1 = Web(query)
val f2 = Image(query)
val f3 = Video(query)
val t = timeout(80.milliseconds)

// using Scala's Future API
val results: Future[Seq[Result]] = for {
  r1 <- or(f1)(t)
  r2 <- or(f2)(t)
  r3 <- or(f3)(t)
} yield (r1.toSeq ++ r2.toSeq ++ r3.toSeq)

// OR using async
val results: Future[Seq[Result]] = async {
  val r1 = or(f1)(t)
  val r2 = or(f2)(t)
  val r3 = or(f3)(t)
  await(r1).toSeq ++ await(r2).toSeq ++ await(r3).toSeq
}

// or and timeout are utility/library functions defined below

def or[T](f1: Future[T])(f2: Future[Option[Nothing]]): Future[Option[T]] =
  Future.firstCompletedOf(f1 map Some.apply, f2)

// create a future that will complete successfully with None
// after the given duration passes
def timeout(d: Duration): Future[Option[Nothing]] = {
  val p = Promise[Option[Nothing]]
  Scheduler.after(d) { p success None }
  p.future
}