async & await
async and await let you write asynchronous code that reads like synchronous code. Under the hood it's still futures and the event loop, but the compiler turns your straight-line code into the callback chain for you.
The basics
- Mark a function
async. It now always returns aFuture—return 5;in anasyncfunction returningFuture<int>completes the future with5. - Inside it,
await someFuturepauses this function until the future completes, then gives you its value. Other work keeps running meanwhile.
Future<String> fetchUserName(int id) async {
await Future.delayed(Duration(milliseconds: 20)); // simulate network
return id == 1 ? 'Lan' : 'Guest';
}
Future<int> fetchOrderCount(String user) async {
await Future.delayed(Duration(milliseconds: 10));
return user.length * 3;
}
Future<void> main() async {
print('loading...');
final name = await fetchUserName(1);
final count = await fetchOrderCount(name);
print('$name has $count orders');
}loading...
Lan has 9 orders
Compare with the then version: fetchUserName(1).then((name) => fetchOrderCount(name).then((count) => print(...))). With await, variables stay in scope and the code reads top to bottom.
What happens at await
await gives control back to the event loop. Code after the call to an async function may run before the async function finishes:
Future<void> brew() async {
print(' brew: start');
await Future.delayed(Duration(milliseconds: 10));
print(' brew: coffee ready');
}
Future<void> main() async {
print('A');
final pending = brew(); // runs synchronously until its first await
print('B');
await pending;
print('C');
}A
brew: start
B
brew: coffee ready
C
An async function runs synchronously up to its first await, then returns an uncompleted future to its caller.
Sequential vs concurrent
Awaiting one by one runs operations sequentially. If they're independent, start them all first and await together:
Future<int> slowSquare(int n) async {
await Future.delayed(Duration(milliseconds: 50));
return n * n;
}
Future<void> main() async {
final sw = Stopwatch()..start();
final a = await slowSquare(2);
final b = await slowSquare(3);
final c = await slowSquare(4);
final sequentialMs = sw.elapsedMilliseconds;
print('sequential: ${a + b + c}');
sw.reset();
final results = await Future.wait([slowSquare(2), slowSquare(3), slowSquare(4)]);
final concurrentMs = sw.elapsedMilliseconds;
print('concurrent: ${results.reduce((x, y) => x + y)}');
final (x, y) = await (slowSquare(5), slowSquare(6)).wait; // Dart 3 record form
print('record wait: $x, $y');
print('concurrent faster: ${concurrentMs < sequentialMs}');
}sequential: 29
concurrent: 29
record wait: 25, 36
concurrent faster: true
The sequential version takes about 150 ms, the concurrent one about 50 ms.
async loops and await for
You can await inside any loop. For a Stream, await for processes each event as it arrives:
Stream<int> countdown(int from) async* {
for (var i = from; i > 0; i--) {
await Future.delayed(Duration(milliseconds: 5));
yield i;
}
}
Future<void> main() async {
final ids = [3, 1, 2];
for (final id in ids) {
final label = await Future.value('item-$id');
print(label);
}
await for (final n in countdown(3)) {
print('T-$n');
}
print('liftoff');
}item-3
item-1
item-2
T-3
T-2
T-1
liftoff
Return types
| Declaration | Meaning |
|---|---|
Future<int> f() async |
Eventually produces an int |
Future<void> f() async |
Eventually completes, no useful value — callers can await it |
void f() async |
"Fire and forget" — callers can't await it or catch its errors. Avoid except for event handlers. |
FutureOr<T> |
Either a T or a Future<T> (from dart:async) — for APIs accepting both |
Tip: Make
mainreturnFuture<void>and mark itasyncwhenever it awaits something. The program then waits for everything youawaitbefore exiting.
Test yourself
What does an async function that returns 42 actually return to its caller?
- 42
- A Future<int> that completes with 42
- A Stream<int>
- void
Until which point does an async function run synchronously when called?
- It never runs synchronously
- Until its first await
- Until it returns
- Until the next microtask
How do you run two independent async calls concurrently and get both results?
- await a(); await b();
- await Future.wait([a(), b()])
- a().then(b())
- async { a(); b(); }