How to resolve a list of futures in Scala

后端 未结 3 1508
遇见更好的自我
遇见更好的自我 2021-02-02 11:05

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 (w

3条回答
  •  有刺的猬
    2021-02-02 11:43

    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)
    

    which you could also write as:

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

提交回复
热议问题