← → or space · progress saves for Continue on the roadmap
Goal
Chain asynchronous work without callback pyramids.
Step 1 - Future value
Future<int> delayedOne() {
return Future.delayed(const Duration(milliseconds: 100), () => 1);
}
Future<void> main() async {
final n = await delayedOne();
print(n);
}awaitpauses the currentasyncfunction until the future completes; it does not block other tasks on the isolate.
Step 2 - async function
Future<String> fetchLabel() async {
await Future.delayed(const Duration(milliseconds: 50));
return 'ready';
}
Future<void> main() async {
print(await fetchLabel());
}Step 3 - Errors propagate
Future<void> boom() async {
await Future.delayed(const Duration(milliseconds: 10));
throw StateError('no');
}
Future<void> main() async {
try {
await boom();
} catch (e) {
print(e);
}
}Good habit
- Return
Future<void>frommainwhen using top-levelawait(Dart allows asyncmain).
Practice tasks
- Write
Future<int> sumAfterDelays()that awaits twoFuture.valuedelays and returns the sum of two ints. - Call an
asyncfunction withoutawaitand observe thatmaincan finish before it runs; fix by awaiting or returning the future frommain.