Await.result(Seq[Future[T]])

1,625 views
Skip to first unread message

Ian Ferreira

unread,
Apr 25, 2014, 1:17:04 AM4/25/14
to scala...@googlegroups.com
Is there a way to wait for a list or array if futures to complete other than the for-comprehension.

var result = for {

r1 <= future1
r2 <= future2

} yield

I want to at runtime call a unknown amount of functions that return a future then wait for all them to complete. Suppose I had a web page where you can enter a list of urls and I wanted to call them all in parallel and wait for all to return before return to the user. How would I do that?

Paul Keeble

unread,
Apr 25, 2014, 1:57:53 AM4/25/14
to Ian Ferreira, scala-user
One way to go about doing this is with Future.sequence. What it will give you back is a single Future over all your results. So you can then just call map on that from your calling function for your callback when its done. Example:

val a = Future { 1 }
val b = Future { 2 }

val numbers = List(a,b)
val futNumbers = Future.sequence(numbers)

futNumbers.map { listOfNumbers => /* your handling code here */ }

PK


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ian Ferreira

unread,
Apr 27, 2014, 11:07:37 PM4/27/14
to scala...@googlegroups.com, Ian Ferreira
Thanks PK

Which part of the snippet blocks until the features a and b complete?

Paul Keeble

unread,
Apr 28, 2014, 3:11:51 AM4/28/14
to Ian Ferreira, scala-user

None of the original code blocks because you get the callback asynchronously, which depending on what you are looking at may or may not be what you want.

You can go about blocking for the future returned if that is more the plan in which case the final line would be replaced with this:

val theResultingNumbers = Await.result(futNumbers, 10 seconds)

TheResultingNumbers would be a List[Int] which is the result of the future executions.

The duration could potentially be Duration.inf if you don't know how long it blocks for but that has dangers as well if they might not complete.

PK

Ian Ferreira

unread,
Apr 28, 2014, 12:50:26 PM4/28/14
to scala...@googlegroups.com, Ian Ferreira
seems like I can wait on the futModels
Reply all
Reply to author
Forward
0 new messages