Sub topic 5
Chaining with then and catchError
This chapter explains how then, catchError, and whenComplete build a pipeline of asynchronous steps. It assumes you know basic Dart syntax, generics such as Future<int>, anonymous functions, and how to run a program with dart run. It also assumes you know what a Future is: an object that later completes with a value or an error.
Most new Dart code uses async and await, which the next chapter covers. You still need then for three reasons. Older code and library documentation use it. Some situations are shorter with it. And await is built on the same model, so knowing it explains the error behavior you will see later.
The core idea: then returns a new Future
Future<T>.then registers a callback that runs when the Future completes with a value. It does not change the original Future. It returns a new Future that represents the result of your callback.
Future<int> loadCount() =>
Future.delayed(const Duration(milliseconds: 300), () => 7);
Future<String> loadLabel(int count) =>
Future.delayed(const Duration(milliseconds: 200), () => 'item-$count');
void main() {
loadCount()
.then((count) {
print('count: $count');
return loadLabel(count);
})
.then((label) => print('label: $label'))
.whenComplete(() => print('done'));
print('main end');
}The output is:
main end
count: 7
label: item-7
donemain end prints first because main does not wait. It registers callbacks and returns. The event loop, covered in an earlier chapter, runs the callbacks later.
Notice what the first callback returns. It returns a Future<String>, not a String. The Future returned by then does not complete until that inner Future completes, and it takes the inner Future's value. Dart calls this flattening. The second then therefore receives a String, not a Future<String>.
Here is how the callback's return value determines the new Future:
| Callback does this | The Future returned by `then` |
|---|---|
| Returns a plain value `v` | Completes with `v` |
| Returns a Future | Completes the same way that Future does |
| Returns nothing | Completes with `null` (type `Future<void>` when the callback returns `void`) |
| Throws an exception | Completes with that error |
The third row causes a common bug, covered below.
How values and errors travel down a chain
A chain has two paths. A value travels down the success path and runs each then callback in turn. If any step produces an error, the error switches to the error path. It skips every later then callback until it reaches an error handler.
Two consequences follow from this model:
- A single
catchErrorat the end of a chain handles an error from any earlier step. - If
catchErrorreturns a value, the chain recovers. Laterthencallbacks run again with that value. IfcatchErrorrethrows, the error stays on the error path.
Handling errors with catchError
catchError registers a handler for errors. Here is the callback-style code from the spine, next to its async equivalent:
Future<int> loadCount() {
return Future.delayed(const Duration(milliseconds: 300), () => 7);
}
// Callback style
Future<String> describeWithThen() {
return loadCount()
.then((count) => 'Count is $count')
.catchError((Object e) => 'Failed: $e');
}
// Equivalent with async and await
Future<String> describeWithAwait() async {
try {
final count = await loadCount();
return 'Count is $count';
} catch (e) {
return 'Failed: $e';
}
}Both functions return the same result in every case. Each call returns a Future<String>. If loadCount succeeds, the result is Count is 7. If it fails, the result is Failed: ....
The handler must return a compatible value
catchError is called on a Future<T> and returns a Future<T>. Its handler must therefore produce a T, or a Future<T>, or throw. Here is a common mistake:
Future<int> risky() => Future.error(StateError('no data'));
Future<void> main() async {
final value = await risky().catchError((Object e) {
print('logged: $e');
// Missing return: the handler yields null, not an int.
});
print(value);
}The handler logs the error but returns null, and null is not an int. The Future returned by catchError fails with a type error instead of recovering, so the await throws. Return a fallback such as 0, or rethrow the error. Use Future<int?> if null is a legitimate result.
Filtering with test
catchError accepts an optional test argument. It is a function that receives the error and returns true if this handler should handle it. If it returns false, the error passes through to the next handler. This is the callback-style equivalent of an on FormatException catch clause.
Future<int> parse(String text) async => int.parse(text);
Future<void> main() async {
final n = await parse('abc').catchError(
(Object e) => -1,
test: (Object e) => e is FormatException,
);
print(n); // -1
}If parse threw a different exception, the test would return false and the error would continue down the chain.
Two ways to handle errors: onError and catchError
then has an optional named parameter onError. The next example looks similar to catchError but behaves differently:
Future<int> source() => Future.value(1);
void main() {
// The onError handler does NOT see errors thrown by the first callback.
source().then(
(v) => throw StateError('callback failed'),
onError: (Object e) => print('onError saw: $e'),
).catchError((Object e) {
print('catchError saw: $e');
});
}This prints only catchError saw: Bad state: callback failed. The onError parameter handles errors from the Future that then was called on. It does not handle errors thrown by the callback in the same then call. A catchError placed after the then handles both. For this reason, prefer a separate .catchError(...) at the end of the chain.
Cleaning up with whenComplete
whenComplete runs a callback whether the Future completed with a value or with an error. It works like finally:
Future<String> fetchReport() =>
Future.delayed(const Duration(milliseconds: 100), () => 'report');
Future<void> main() async {
var loading = true;
print('loading: $loading');
final report = await fetchReport()
.whenComplete(() => loading = false);
print('loading: $loading, got $report');
}Behavior to know about whenComplete:
- The callback receives no arguments, so it cannot inspect the value or error.
- The Future it returns completes with the original value or error. Your callback's return value is ignored.
- If your callback returns a Future, the result waits for that Future. If that Future fails, or the callback throws, the new error replaces the original result.
Common mistakes in then chains
- Forgetting to return the inner Future. If a
thencallback starts asynchronous work but does not return it, the chain moves on without waiting. Errors from that work also escape the chain. - Nesting instead of chaining. Writing a
theninside athenrecreates the deeply indented "callback pyramid" that Futures were meant to avoid. Return the inner Future and chain at the outer level. - Not returning the chain. A function that builds a chain but does not return the final Future gives its caller nothing to await or catch errors from.
- Handler return type mismatch. The
catchErrorhandler must return a value assignable to the Future's type, as shown above.
This example shows the first mistake:
Future<void> save(String name) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
print('saved $name');
}
Future<void> main() async {
// Bug: save() is not returned, so the chain does not wait for it.
await Future.value('a').then((name) {
save(name);
});
print('after chain');
}after chain prints before saved a. The fix is return save(name);, or the arrow form (name) => save(name).
Converting a chain to async and await
You can convert a chain mechanically:
- Mark the function
async. - Replace each
.then((x) => ...)withfinal x = await ...;. - Move the code from the
thencallbacks into the lines that follow. - Replace
.catchErrorwithtry/catch. - Replace
.whenCompletewithfinally.
The chain from the start of this chapter becomes:
Future<int> loadCount() =>
Future.delayed(const Duration(milliseconds: 300), () => 7);
Future<String> loadLabel(int count) =>
Future.delayed(const Duration(milliseconds: 200), () => 'item-$count');
Future<void> main() async {
try {
final count = await loadCount();
print('count: $count');
final label = await loadLabel(count);
print('label: $label');
} catch (e) {
print('failed: $e');
} finally {
print('done');
}
}The two forms behave the same. Chains are still convenient for short, one-expression transformations such as fetchName().then((n) => n.toUpperCase()). They also fit when you want to attach a handler to a Future without making the surrounding function async.
Exercise
This function should return the length of a name, or 0 if loading fails. It has two bugs. What are they, and what is the corrected code? Future<String> loadName() => Future.error(Exception('offline')); Future<int> nameLength() { loadName().then((name) => name.length).catchError((Object e) { print('error: $e'); }); }
Show answer
Bug 1: the function never returns the chain, so the caller gets no Future (this will not compile for a function that must return Future<int>). Bug 2: the catchError handler returns nothing, so it cannot produce the int that the Future<int> requires. Corrected code: Future<int> nameLength() { return loadName().then((name) => name.length).catchError((Object e) { print('error: $e'); return 0; }); } Here the error skips the then callback, and the handler recovers with 0.