DART / CHAPTER 11
Futures and failure boundaries
AdvancedAwait asynchronous work and handle its errors deliberately.
By the end of this chapter
- Read Future result types
- Trace execution around await
- Catch a failed awaited operation
The idea
A Future represents a result that may become available later, or an error that prevents that result. An async function returns a Future and can use await to pause its own progress until another future completes. This does not mean the whole program is blocked; other scheduled work can run while the asynchronous function is waiting.
Place try/catch around an awaited call when that boundary can recover or report the failure. A future returned without awaiting is still an asynchronous value, not its completed result. Keep the successful result path distinct from the error path, and avoid launching work without observing its completion when correctness depends on whether that work succeeds.
Future<int> readCount() async => 6;
Future<void> main() async {
print("start");
final count = await readCount();
print(count + 1);
print("done");
}start 7 done
The function resumes after readCount completes with six. The following statements use that value and then print the completion label.
Try it yourself
Write an async wrapper that awaits a count and returns zero only for a documented expected failure.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING