Sub topic 5
Chaining with `then` and `catchError`
Assume you know basic Dart functions, callbacks, generics, and how to run a program with dart run. This chapter uses callback-style Future chains. Later, the same work can be written with async and await.
How a `Future` chain works
A Future<T> represents a result that will eventually contain a value of type T or an error. The then method registers a callback for the successful result:
future.then((value) {
// Use value here.
});then returns another Future. That returned future represents whatever the callback returns. This lets you transform one asynchronous result into another:
loadUser()
.then((user) => loadOrders(user.id))
.then((orders) => print(orders));The first callback receives the user. Its returned future becomes the input to the second callback. If a callback returns an ordinary value, the next future completes with that value. If it returns a future, Dart waits for that future before continuing the chain.
Handling failures with `catchError`
Use catchError to handle an error from the source future or from an earlier callback. If the error handler returns a replacement value, the chain can continue successfully. If it throws another error, the returned future remains failed.
import 'dart:async';
Future<int> loadCount() {
return Future.delayed(
const Duration(milliseconds: 300),
() => 7,
);
}
Future<String> describeWithThen() {
return loadCount()
.then((count) => 'Count is $count')
.catchError((Object error) => 'Failed: $error');
}
Future<void> main() async {
print(await describeWithThen());
final failed = Future<int>.error(StateError('server unavailable'));
final recovered = failed
.then((count) => 'Count is $count')
.catchError((Object error) => 'Using a default value')
.whenComplete(() => print('request finished'));
print(await recovered);
}In this example, catchError changes the failed Future<String> into a successful future containing "Using a default value". The whenComplete callback runs whether the chain succeeds or fails. Use it for cleanup or logging, not for changing the result.
The error handler must return a value compatible with the chain's type. In production code, prefer a specific error type when possible:
.catchError((Object error) {
if (error is TimeoutException) {
return 'The request took too long';
}
throw error;
});A handler that does not recognize an error should rethrow it so another layer can handle it.
Common chaining mistakes
- Forgetting to return a future from a callback breaks the intended sequence.
``dart saveUser().then((_) { sendEmail(); // The chain does not wait for this future. }); ``
Return it when the next operation must wait:
``dart saveUser().then((_) => sendEmail()); ``
- Creating a chain without awaiting or otherwise observing its final future can leave errors unhandled. At the boundary of an asynchronous function, return the chain or use
await.
- Putting
catchErrortoo early can cause later callbacks to run outside the error handler. Put it after the operations it should protect, or add separate handlers for separate recovery decisions.
- Use
whenCompletefor cleanup, but remember that it does not suppress an error. The original success or failure continues after it runs.
Exercise
What value does this expression produce if loadCount() completes with 5? loadCount().then((n) => n * 2).then((n) => 'Total: $n')
Show answer
It produces a successful Future<String> containing Total: 10.