Sub topic 8
Running work sequentially or in parallel
Assume you know basic Dart functions, Future<T>, callbacks, and how to run a program with dart run. This chapter focuses on choosing whether asynchronous operations should wait for one another or start together.
Sequential asynchronous work
Sequential work runs one operation after another. The next operation does not start until the previous operation finishes. This is necessary when one result is an input to the next operation.
For example, loading a user before loading that user's orders is sequential:
final user = await loadUser();
final orders = await loadOrders(user.id);The second function needs user.id, so starting both operations at the same time would not work.
Sequential code can also be correct but unnecessarily slow when operations are independent. In the following example, the second call starts only after the first call finishes:
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 500), () => n * n);
Future<void> main() async {
final watch = Stopwatch()..start();
final first = await slowSquare(2);
final second = await slowSquare(3);
print('results: [$first, $second]');
print('elapsed: ${watch.elapsedMilliseconds} ms');
}Each operation takes about 500 milliseconds, so the total usually takes about one second.
Parallel asynchronous work with Future.wait
Independent operations can start together. Call each function before awaiting its result, then pass the Futures to Future.wait.
Future.wait is a function that waits for several Futures and returns their results as a list. The result order matches the input order, even if the operations finish in a different order.
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 500), () => n * n);
Future<void> main() async {
final watch = Stopwatch()..start();
final futures = <Future<int>>[
slowSquare(2),
slowSquare(3),
];
final results = await Future.wait(futures);
print('results: $results');
print('elapsed: ${watch.elapsedMilliseconds} ms');
}Both calls begin while the list is being created. The program then waits for both. The total usually takes about 500 milliseconds, close to the duration of the slower operation.
| Strategy | When the next operation starts | Typical duration for two 500 ms operations |
|---|---|---|
| Sequential `await` | After the previous operation finishes | About 1,000 ms |
| `Future.wait` | Immediately with the other operations | About 500 ms |
Errors and cancellation
By default, Future.wait completes with an error if one of its Futures fails. The await expression then throws that error, so handle it with try and catch.
Future<String> loadPart(String name) async {
if (name == 'bad') {
throw StateError('Could not load $name');
}
return 'loaded $name';
}
Future<void> main() async {
try {
final parts = await Future.wait([
loadPart('header'),
loadPart('bad'),
loadPart('footer'),
]);
print(parts);
} on StateError catch (error) {
print('Loading failed: $error');
}
}Future.wait does not automatically cancel the other operations when one fails. Those operations may continue running. If they perform external work, such as an HTTP request, use an API that supports cancellation when cancellation matters.
> callout warning > Do not use Future.wait merely because it is faster. Use it only when the operations are independent and the application can handle their combined failure behavior.
A common mistake is awaiting each Future immediately:
final first = await slowSquare(2);
final second = await slowSquare(3);This is sequential. To run them together, create both Futures first:
final firstFuture = slowSquare(2);
final secondFuture = slowSquare(3);
final results = await Future.wait([firstFuture, secondFuture]);Use sequential execution for dependencies, ordering requirements, or resource limits. Use Future.wait for independent work that can safely run concurrently.
Exercise
Two independent database queries each take 400 milliseconds. Which approach should you use to reduce waiting time, and what result does it produce?
Show answer
Start both queries first and await Future.wait on them. The returned list keeps the same order as the input Futures, and the total time is usually close to 400 milliseconds rather than 800.