Sub topic 2
Chaining with then and catchError
This chapter assumes you know Dart functions, generics such as Future<int>, and how to run a program with dart run. You should also understand that a Future holds a value that arrives later.
Chaining with then and catchError
then runs a callback when a Future completes with a value. catchError runs a callback when it completes with an error. Each call returns a new Future, so you can chain them.
Future<int> loadCount() {
return Future.delayed(const Duration(milliseconds: 300), () => 7);
}
Future<String> describeWithThen() {
return loadCount()
.then((count) => 'Count is $count')
.catchError((Object e) => 'Failed: $e');
}Writing async functions with await
An async function always returns a Future. Inside it, await pauses that function until a Future completes, then gives you the value. The code reads like synchronous code.
Future<String> describeWithAwait() async {
final count = await loadCount();
return 'Count is $count';
}Handling errors in asynchronous code
When a Future completes with an error, await rethrows it. This lets try, catch, and finally handle async errors the same way they handle synchronous ones.
Future<String> fetchData() async {
throw Exception('network down');
}
Future<String> loadWithFallback() async {
try {
return await fetchData();
} catch (e) {
return 'fallback';
}
}
Future<void> main() async {
print(await loadWithFallback());
}Running work sequentially or in parallel
Awaiting operations one at a time takes about the sum of their durations. Future.wait starts all of them at once and returns their results as a list, in the original order.
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');
}Exercise
The sequential version takes about 1000 ms, but Future.wait takes about 500 ms. Why?
Show answer
The two await calls run one after the other, so their 500 ms delays add up. Future.wait starts both calls before it waits, so the total is roughly the time of the slower call.