Reputation: 14266
I need to wait for many Future
to complete their computation, a bunch of HTTP requests, I don't want to await
all of them in order as this will result in each Future
being evaluated in order, one after the other, kinda synchronously, which is wasteful as some Future
might complete sooner than others.
I can't find in the docs of Future.wait
is truly asynchronous, firing all the Future
at the same time, or if its the same as calling them one after the other, waiting for the previous to complete to call the next.
In a nushell: I am looking for the best performant way to get the results of many HTTP requests in Dart.
Upvotes: 0
Views: 700
Reputation: 24641
Future.wait
does await multiple futures in an asynchronous way, as in each of the futures is started independently of one another. By contrast, Future.forEach
will loop through the list of futures and await on them in sequence.
For example, if you had the following list of futures:
var futures = [
Future.delayed(Duration(seconds, 3)).then((_) => print('1')),
Future.delayed(Duration(seconds, 2)).then((_) => print('2')),
Future.delayed(Duration(seconds, 1)).then((_) => print('3')),
];
Calling Future.wait
on this list would result in the following output:
3 (after 1 second)
2 (after 2 seconds)
1 (after 3 seconds)
Whereas calling Future.forEach
on the list would result in this:
1 (after 3 seconds)
2 (after 5 seconds)
3 (after 6 seconds)
This is because wait
fires them all simultaneously then handles them as they all resolve while forEach
fires them individually in order and waits for each one to resolve before going to the next one.
(Here is the usual disclaimer that asynchronous programming is not the same thing as parallel programming, and that Dart is an inherently single-threaded language so true parallelism cannot be achieved with futures alone.)
Upvotes: 3
Reputation: 31209
If you check the implementation of the Future.wait
method in:
You can actually see it goes through each Future
in the input list and runs the then
method which a method to be run when the Future
completes:
for (var future in futures) {
int pos = remaining;
future.then((T value) {
...
You could therefore say that all Future
instances are "started" at the same time since each completed Future
will end up checking if there are more futures to wait for.
However, please note that Dart is single threaded with a job queue behind the scene, so unless some of the work are done in Isolate
instances, each job will end up running in serial. More details about this can be found here:
https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a
But yes, if you have a bunch if Future
's which can be handles in any order it makes sense to use the Future.wait
method.
Upvotes: 1