Sub topic 8
Running work sequentially or in parallel
This chapter assumes you can write async functions, use await, and read Future<T> types. Chapter 6 covered those. Here you decide when await should run operations one after another and when they should run at the same time. You also learn how errors, timing, and limits on concurrency change with that choice.
Sequential by default
await pauses the current async function until a Future completes. When you write two awaits in a row, the second operation does not start until the first has finished:
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 500), () => n * n);
Future<void> main() async {
final sw = Stopwatch()..start();
final a = await slowSquare(2);
final b = await slowSquare(3);
print('sequential: [$a, $b] in ${sw.elapsedMilliseconds} ms');
}This prints roughly sequential: [4, 9] in 1000 ms. The total time is the sum of the two durations.
Sequential execution is correct when the second step needs the first step's result. For example, you cannot fetch a user's orders before you know the user's ID. It is wasteful when the operations are independent.
Parallel with Future.wait
Future.wait takes an iterable of Futures and returns one Future that completes when all of them have completed. Its value is a list of the results, in the same order as the input.
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 500), () => n * n);
Future<void> main() async {
final sw = Stopwatch()..start();
final a = await slowSquare(2);
final b = await slowSquare(3);
print('sequential: [$a, $b] in ${sw.elapsedMilliseconds} ms');
sw.reset();
final results = await Future.wait([slowSquare(2), slowSquare(3)]);
print('parallel: $results in ${sw.elapsedMilliseconds} ms');
}The parallel version prints roughly parallel: [4, 9] in 500 ms. The total time is about that of the slowest operation.
"Parallel" needs a precise reading here. Dart runs your code on one thread. Both calls to slowSquare start immediately, and both timers run at the same time. The two operations overlap while they wait. Overlapping waits is where the time saving comes from: network requests, timers, and file reads. Two pieces of Dart code that compute something do not run simultaneously inside one isolate. The last chapter of this tutorial covers that case.
Starting first, awaiting later
A Future begins working when you call the function that creates it, not when you await it. That gives you a second way to run work in parallel:
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 500), () => n * n);
Future<void> main() async {
final sw = Stopwatch()..start();
final futureA = slowSquare(2);
final futureB = slowSquare(3);
final a = await futureA;
final b = await futureB;
print('[$a, $b] in ${sw.elapsedMilliseconds} ms');
}This takes about 500 ms, the same as Future.wait. It is useful when you want to do other work between starting and awaiting.
It has one hazard. If futureB fails while main is still waiting on futureA, nobody is listening to futureB yet. Dart reports an unhandled error, which can terminate the program, even though a later await futureB is inside a try block. Future.wait attaches a listener to every Future immediately, so it avoids this problem. Prefer Future.wait when more than one of the Futures can fail.
Mixed result types with record wait
Future.wait on a list needs one element type, so mixed results lose their types. Since Dart 3, a record of Futures has a .wait getter that keeps each type:
import 'dart:async';
Future<String> fetchName() =>
Future.delayed(const Duration(milliseconds: 300), () => 'Ada');
Future<int> fetchScore() =>
Future.delayed(const Duration(milliseconds: 400), () => 42);
Future<void> main() async {
final (name, score) = await (fetchName(), fetchScore()).wait;
print('$name scored $score');
}name is a String and score is an int, with no casts. The total time is about 400 ms.
Processing a collection
A common task is running the same async operation for every item in a list. The two obvious shapes give different timing:
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 200), () => n * n);
Future<void> main() async {
final inputs = [1, 2, 3, 4, 5];
var sw = Stopwatch()..start();
final one = <int>[];
for (final n in inputs) {
one.add(await slowSquare(n));
}
print('for loop: $one in ${sw.elapsedMilliseconds} ms');
sw = Stopwatch()..start();
final all = await Future.wait(inputs.map(slowSquare));
print('map + wait: $all in ${sw.elapsedMilliseconds} ms');
}The for loop takes about 1000 ms because each iteration waits. The map version takes about 200 ms. map is lazy, but Future.wait iterates it immediately, so all five calls start at once.
Avoid inputs.forEach((n) async { ... }). forEach ignores the Future that each callback returns. It finishes right away, and your code continues before the work is done. Use a for loop for sequential work or Future.wait(inputs.map(...)) for parallel work.
Errors in Future.wait
When one Future in the group fails, the Future from Future.wait completes with an error. By default it still waits for every other Future to finish first. The eagerError parameter changes that:
Future<int> succeedAfter(int ms) =>
Future.delayed(Duration(milliseconds: ms), () => ms);
Future<int> failAfter(int ms) => Future.delayed(
Duration(milliseconds: ms),
() => throw StateError('failed after $ms ms'),
);
Future<void> main() async {
for (final eager in [false, true]) {
final sw = Stopwatch()..start();
try {
await Future.wait(
[succeedAfter(100), failAfter(200), succeedAfter(500)],
eagerError: eager,
);
} on StateError catch (e) {
print('eagerError=$eager: ${e.message} at '
'${sw.elapsedMilliseconds} ms');
}
}
}With eagerError: false (the default), the error surfaces after about 500 ms, once every Future has finished. With eagerError: true, it surfaces after about 200 ms, at the first failure.
Three details matter:
- Setting
eagerError: truedoes not cancel the other Futures. They keep running, and their results are discarded. - If several Futures fail, only one error is reported. You cannot see the rest.
- When you need every success value even if some operations fail, you have two options. You can wrap each operation so it returns a result instead of throwing, or you can use the record form. Its
ParallelWaitErrorexposes both the values and the errors that were collected.
The first option looks like this:
Future<int> succeedAfter(int ms) =>
Future.delayed(Duration(milliseconds: ms), () => ms);
Future<int> failAfter(int ms) => Future.delayed(
Duration(milliseconds: ms),
() => throw StateError('failed after $ms ms'),
);
Future<int?> orNull(Future<int> f) async {
try {
return await f;
} catch (_) {
return null;
}
}
Future<void> main() async {
final results = await Future.wait([
orNull(succeedAfter(100)),
orNull(failAfter(200)),
orNull(succeedAfter(300)),
]);
print(results); // [100, null, 300]
}The wrapper catches the error inside each task, so Future.wait never sees a failure and always returns a full list.
Limiting concurrency
Starting everything at once is not always safe. A thousand simultaneous HTTP requests may exceed a server's rate limit or use up sockets. A simple fix is to process the input in batches. Each batch runs in parallel, and the batches run one after another:
Future<int> slowSquare(int n) =>
Future.delayed(const Duration(milliseconds: 200), () => n * n);
Future<List<int>> squareInBatches(List<int> inputs, int batchSize) async {
final results = <int>[];
for (var i = 0; i < inputs.length; i += batchSize) {
final end = i + batchSize < inputs.length ? i + batchSize : inputs.length;
final batch = inputs.sublist(i, end);
results.addAll(await Future.wait(batch.map(slowSquare)));
}
return results;
}
Future<void> main() async {
final sw = Stopwatch()..start();
final squares = await squareInBatches([1, 2, 3, 4, 5, 6], 3);
print('$squares in ${sw.elapsedMilliseconds} ms');
}Six items in batches of three take about 400 ms. That is two batches of 200 ms each, compared with 1200 ms sequentially and 200 ms unbounded. A batch must finish completely before the next starts, so one slow item holds up the whole batch. A worker pool avoids that, but it needs more code, and a package such as pool is a common choice.
Choosing between them
| Situation | Approach | Total time |
|---|---|---|
| Step two needs step one's result | `await` one after the other | Sum of durations |
| Independent operations, same type | `Future.wait` on a list | Slowest operation |
| Independent operations, different types | Record `.wait` | Slowest operation |
| Many items, server or resource limits | Batches of `Future.wait` | Sum of batch durations |
| Independent, and you want other work in between | Start Futures, await later | Slowest operation |
Summary of rules
- Each
awaitis a waiting point. Consecutive awaits on independent Futures waste time. - A Future starts when it is created.
Future.waitis the safe way to await several at once. Future.waitreturns results in input order, regardless of which finishes first.- One failure fails the whole group. Decide between
eagerError, per-task wrappers, or the record form depending on whether you need partial results. - Overlapping waits is not the same as running Dart code on several threads.
Exercise
The code below is meant to fetch three user names in parallel, but it takes about 900 ms instead of 300 ms. Why, and how do you fix it? Future<String> fetchUser(int id) => Future.delayed(const Duration(milliseconds: 300), () => 'user$id'); Future<void> main() async { final names = <String>[]; for (final id in [1, 2, 3]) { names.add(await fetchUser(id)); } print(names); }
Show answer
Each loop iteration awaits fetchUser before the next call starts, so the three 300 ms delays add up to about 900 ms. Create all the Futures first and wait for them together: final names = await Future.wait([1, 2, 3].map(fetchUser));. All three calls start immediately, and the total time is about 300 ms.
Exercise
You call Future.wait([a(), b(), c()]). Function b() fails after 100 ms, while a() and c() each need 2 seconds. With the default settings, when does your catch block run, and what happens to the other two operations if you pass eagerError: true?
Show answer
With the default eagerError: false, the catch block runs after about 2 seconds, once all three Futures have completed. With eagerError: true, it runs after about 100 ms. The other two operations are not cancelled. They keep running, and their results are ignored.