gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:16 26 4
gpt4 key购买 nike

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

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

最佳答案

这是如何完成的草图(未经测试;我不声称这是最佳解决方案):

// 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
}

关于c# - 您将如何使用 Scala 的异步使多个异步请求超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com