如何解析斯卡拉的期货清单 [英] How to resolve a list of futures in Scala

查看:78
本文介绍了如何解析斯卡拉的期货清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回Future的电话. 但是,我需要拨打n次电话,这样我才能收回n次期货.我想知道在继续操作之前如何解决期货问题(不阻塞服务器)

I have a call that returns a Future. However, I need to make n calls so I will get back n futures. I am wondering how I would get the futures to all resolve before proceeding (without blocking the server)

例如

while(counter < numCalls){
    val future = call(counter)
    future.map{  x =>
        //do stuff
    }
    counter += 1 
}

//Now I want to execute code here after ALL the futures are resolved without 
//blocking the server

推荐答案

您可以使用Future.sequence(futureList)List[Future[X]]转换为Future[List[X]].而且由于后者只是一个简单的Future,因此您可以在Await.ready或类似的帮助程序的帮助下等待它结束.

You can use Future.sequence(futureList) to convert a List[Future[X]] to a Future[List[X]]. And since the latter is just a simple Future, you can wait for it to finish with the help of the Await.ready or similar helpers.

因此,您将必须保留一份所产生的期货清单.像这样:

So you would have to keep a list of the futures you generate. Something like:

val futures = new ListBuffer[Future[X]]
while(counter < numCalls) {
    val future = call(counter)
    futures += future
    future.map { x =>
        //do stuff
    }
    counter += 1 
}
val f = Future.sequence(futures.toList)
Await.ready(f, Duration.Inf)

您也可以这样写:

val futures = (1 to numCalls).map(counter => {
    f = call(counter)
    f.map(x => ...)
    f
})
Await.ready(Future.sequence(futures), Duration.Inf)

这篇关于如何解析斯卡拉的期货清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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