Dart
Future.wait
Learn parallel Futures with Future.wait.
Future.wait
To start many Futures in parallel and wait for all of them you use Future.wait. It takes a list of Futures and returns a list of values when all complete. Parallel work is much faster than sequential await.
Example: final result = await Future.wait([Future.value(1), Future.value(2), Future.value(3)]);. result is a List<int> holding [1, 2, 3]. The three Futures run in parallel; when all finish Future.wait completes. If one Future fails Future.wait also fails. Inside an async function you wait with await; you can also chain with .then.
Exercise Your turn: wait in parallel
Mark Future<void> main() async. Wait for three parallel Futures with final result = await Future.wait([Future.value(1), Future.value(2), Future.value(3)]);. Then print the list with print(result).
Show example solution
Future<void> main() async {
final result = await Future.wait([Future.value(1), Future.value(2), Future.value(3)]);
print(result);
}
Parallel vs sequential
If you await three Futures one by one the total time is the sum of their durations. With Future.wait you start them in parallel and the total is the slowest one. If each Future takes 1 second, sequential takes 3 seconds, parallel takes 1 second.
So running independent tasks in parallel is a good habit. But be careful: dependent tasks cannot run in parallel; if the second waits for the first's result you must go sequential. Inside Future.wait every Future must have the same type; for different types you use a common supertype. On error one failing Future fails the whole Future.wait; with eagerError: false you can wait for the rest.
Test yourself
-
Future.wait
final result = await ____([Future.value(1), Future.value(2)]);
Show answer
final result = await Future.wait([Future.value(1), Future.value(2)]);
-
Fastest way to wait for three independent Futures?
final a = await Future.wait([
Future.value(1),
Future.value(2),
Future.value(3),
]);
- Sequential await
- .then chain
- Future.wait in parallel
- try/catch
Show answer
Future.wait in parallel — Future.wait runs in parallel; it is the fastest.
-
Match Future.wait
- Future.wait
- waits in parallel
- List<Future>
- input list
- List<T>
- output list
- eagerError
- error behavior
Next lesson: Summary - Async basics