Async and Practical
Futures
async and await
An async function returns a Future. await suspends until that future completes.
Program
Play the program to await an asynchronous name and greet.
futures.dart
Replay: real traced execution (multi-file project)
Future<String> fetchName() async {
await Future.delayed(Duration.zero);
return 'Ada';
}
Future<void> main() async {
var name = await fetchName();
print('Hello, $name');
}
call ← await fetchName()
6Future<void> main() async {7 var name = await fetchName();8 print('Hello, $name');values this stepawait fetchName()callawaiting ← Future.delayed(zero)
1Future<String> fetchName() async {2 await Future.delayed(Duration.zero);3 return 'Ada';values this stepFuture.delayed(zero)awaitingreturn value ← Future<String> -> Ada
2 await Future.delayed(Duration.zero);3 return 'Ada';4}values this stepFuture<String> -> Adareturn valuename ← Ada
6Future<void> main() async {7 var name = await fetchName();8 print('Hello, $name');values this stepAdanameprint('Hello, $name');
7 var name = await fetchName();8 print('Hello, $name');9}outputHello, Adavalues this stepAdaname
async
An `async` function returns a `Future` automatically.
await
`await` pauses the function until the future resolves.
event loop
`Future.delayed(Duration.zero)` yields to the event loop.