猿问

您将如何使用 Scala 的异步超时多个异步请求?

我不知道 Scala,但我很好奇它的异步功能(类似于 C# 的)。你如何将这个 go 代码翻译成 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


蓝山帝景
浏览 178回答 1
1回答

慕村225694

这是如何完成的草图(未经测试;我不声称这是最好的解决方案):// 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 APIval results: Future[Seq[Result]] = for {&nbsp; r1 <- or(f1)(t)&nbsp; r2 <- or(f2)(t)&nbsp; r3 <- or(f3)(t)} yield (r1.toSeq ++ r2.toSeq ++ r3.toSeq)// OR using asyncval results: Future[Seq[Result]] = async {&nbsp; val r1 = or(f1)(t)&nbsp; val r2 = or(f2)(t)&nbsp; val r3 = or(f3)(t)&nbsp; await(r1).toSeq ++ await(r2).toSeq ++ await(r3).toSeq}// or and timeout are utility/library functions defined belowdef or[T](f1: Future[T])(f2: Future[Option[Nothing]]): Future[Option[T]] =&nbsp; Future.firstCompletedOf(f1 map Some.apply, f2)// create a future that will complete successfully with None// after the given duration passesdef timeout(d: Duration): Future[Option[Nothing]] = {&nbsp; val p = Promise[Option[Nothing]]&nbsp; Scheduler.after(d) { p success None }&nbsp; p.future}
随时随地看视频慕课网APP

相关分类

Go
我要回答