Sub topic 6
Writing async functions with await
This chapter assumes you know basic Dart syntax, generics such as Future<int>, and anonymous functions. It also assumes you have read the earlier chapters on the event loop and on what a Future is. Here you will learn what async and await do, in what order the code runs, and how to turn a then chain into straight-line code.
What async and await are
async and await are syntax over the Future machinery you already know. They add no new runtime concept. The compiler rewrites an async function into a state machine that registers callbacks on Futures for you.
asyncgoes between the parameter list and the body. It marks the function as asynchronous.- An
asyncfunction always returns aFuture. You write the value you want, and Dart wraps it. awaitgoes in front of an expression that produces a Future. It pauses the current function until that Future completes, then gives you the result or throws the error.
Here is the smallest useful example:
Future<String> fetchGreeting() {
return Future.delayed(const Duration(seconds: 1), () => 'Hello');
}
Future<void> main() async {
print('before');
final greeting = await fetchGreeting();
print(greeting);
print('after');
}The output is before, then about one second of silence, then Hello and after. The code reads top to bottom, as synchronous code does. The pause does not block the program, because only this function waits. The event loop stays free to run other work.
What await really pauses
await suspends the function, not the thread. When execution reaches an await on a Future that is not yet complete, three things happen:
- The function saves its local variables and its position.
- Control returns to whoever called the function. The caller receives an incomplete
Future. - When the awaited Future completes, the event loop schedules the rest of the function as a continuation, and execution resumes after the
await.
The part before the first await runs synchronously
Many learners assume a function marked async starts later. It does not. The body runs synchronously, as a normal call would, until it reaches the first await. Only then does it return to the caller.
Future<void> greet() async {
print('greet: start');
await Future<void>.delayed(const Duration(milliseconds: 100));
print('greet: after await');
}
void main() {
print('main: before call');
final f = greet();
print('main: after call');
f.then((_) => print('main: greet finished'));
}The output is:
main: before call
greet: start
main: after call
greet: after await
main: greet finishedgreet: start prints before main: after call. The call runs the body up to the await, and only then does greet() hand back an unfinished Future. The diagram shows this order.
This matters when you read logs. An async function that does side effects before its first await does them at call time.
Return values are wrapped for you
Inside an async function, return takes a plain value of type T, and the caller receives a Future<T>. You do not build the Future yourself.
Future<int> doubled(int n) async {
return n * 2;
}
Future<int> doubledArrow(int n) async => n * 2;
Future<void> main() async {
print(await doubled(21));
print(await doubledArrow(4));
}The output is 42 and then 8. If you return a Future from an async function, Dart flattens it. A function declared as Future<int> can return either an int or a Future<int>. The result is never a Future<Future<int>>.
| Declared return type | What you write with `return` | What the caller gets |
|---|---|---|
| `Future<int>` | An `int` or a `Future<int>` | A `Future<int>` |
| `Future<void>` | Nothing | A `Future<void>` that completes when the body ends |
| `Future<String?>` | A `String` or `null` | A `Future<String?>` |
Use Future<void> for async functions that produce no value, and avoid plain void. A void return type gives callers nothing to await, so they cannot know when the work finishes or catch its errors. The one common exception is a framework callback that must be void, such as a Flutter button handler.
Where await is allowed
You can use await only inside a function whose body is marked async (or async*, covered in a later chapter). Writing it elsewhere is a compile-time error:
Future<int> loadCount() async => 7;
void broken() {
// Error: 'await' can only be used in 'async' or 'async*' methods.
// final n = await loadCount();
}Two consequences follow:
- Async spreads upward. If a function awaits something, it must itself be
async, and its callers must either await it or accept an unfinished Future. Dart has no way to wait for a Future inside a synchronous function without blocking. maincan beFuture<void> main() async. Dart then waits for the program's pending work to finish before it exits.
You can also write await on a value that is not a Future. await 5 gives 5. It still yields to the event loop for one turn, which is rarely useful. The await_only_futures lint flags such cases.
Converting a then chain to async and await
The conversion is mechanical. Each .then((value) => ...) becomes final value = await ...;, and the callback body becomes the lines that follow. Here are two helper functions and a then version:
Future<String> fetchUserName(int id) =>
Future.delayed(const Duration(milliseconds: 100), () => 'user$id');
Future<List<String>> fetchPosts(String user) =>
Future.delayed(const Duration(milliseconds: 100), () => ['$user-a', '$user-b']);
Future<int> postCountWithThen(int id) {
return fetchUserName(id)
.then((name) => fetchPosts(name))
.then((posts) => posts.length);
}
Future<int> postCountWithAwait(int id) async {
final name = await fetchUserName(id);
final posts = await fetchPosts(name);
return posts.length;
}
Future<void> main() async {
print(await postCountWithThen(1));
print(await postCountWithAwait(1));
}Both versions print 2. The await version has the advantages that usually decide the choice:
- Intermediate values such as
namestay in scope for later lines. In athenchain you must nest callbacks or pass the values along. - Loops and
ifstatements work naturally around awaits. Athenchain needs recursion or helper functions. - Errors use
try/catch, which the next chapter covers.
then is still the right tool in a few places. One is firing off a side effect without suspending the current function. Another is attaching a callback to a Future you were handed, in a function that cannot be async.
Awaiting in loops and conditions
Because await is an expression inside ordinary statements, you can use it in loops. A for loop with await runs its iterations one after another:
Future<String> fetchTitle(int id) =>
Future.delayed(const Duration(milliseconds: 200), () => 'Title $id');
Future<void> main() async {
final sw = Stopwatch()..start();
for (final id in [1, 2, 3]) {
final title = await fetchTitle(id);
print('$title after ${sw.elapsedMilliseconds} ms');
}
}This takes about 600 ms, because each iteration waits for the previous one. That is correct when each step needs the previous result. When the iterations are independent, it is slower than necessary. A later chapter shows how Future.wait runs them together.
forEach is a trap here. In items.forEach((x) async { await work(x); }), the callback returns a Future that forEach ignores. The loop finishes at once, and nothing waits for the work. Use a for loop when you need to await inside it.
Common errors with async and await
| Mistake | What happens | Fix |
|---|---|---|
| Calling an async function without `await` | The code continues before the work finishes, and any error is not caught by your `try` | Add `await`, or deliberately wrap the call with `unawaited` from `dart:async` |
| Using the Future as if it were the value | A compile error such as "The getter 'length' isn't defined for the type 'Future<List<String>>'" | Await the call first |
| Declaring a function `async` that never awaits | It still works, but returns a Future for no benefit, and the `unnecessary_async` style hint may appear | Remove `async` unless you need the wrapping or want thrown errors turned into failed Futures |
| Putting `await` in a synchronous function | Compile-time error | Mark the function `async` and change its return type to `Future<T>` |
| Declaring `void` instead of `Future<void>` | Callers cannot await it or catch its errors | Return `Future<void>` |
The first mistake is the most common and the hardest to notice. Compare these two calls:
Future<int> loadCount() =>
Future.delayed(const Duration(milliseconds: 300), () => 7);
Future<void> main() async {
final wrong = loadCount();
print(wrong); // Instance of 'Future<int>'
final right = await loadCount();
print(right); // 7
}Printing Instance of 'Future<int>' almost always means an await is missing. Turn on the unawaited_futures lint in analysis_options.yaml so the analyzer reports every Future you discard by accident.
Exceptions in async functions
An exception thrown inside an async function does not propagate to the caller as a synchronous throw. It completes the returned Future with an error, and the await in the caller rethrows it. Here is a preview of the pattern the next chapter covers:
Future<int> parseAge(String input) async {
final age = int.tryParse(input);
if (age == null) {
throw FormatException('Not a number', input);
}
return age;
}
Future<void> main() async {
try {
print(await parseAge('42'));
print(await parseAge('abc'));
} on FormatException catch (e) {
print('Bad input: ${e.message}');
} finally {
print('done');
}
}The output is 42, Bad input: Not a number, and done. Without the await, the try block would finish before the Future failed, and the catch clause would never run.
Exercise
The function below prints three lines. In what order do they appear, and why? Future<void> task() async { print('A'); await Future<void>.delayed(Duration.zero); print('B'); } void main() { task(); print('C'); }
Show answer
The output is A, C, B. The body of task runs synchronously up to the first await, so A prints during the call. The await returns an incomplete Future to main, which prints C. B prints later, when the event loop runs the delayed callback and resumes task.
Exercise
Rewrite this function using async and await. What does it return when the awaited Future fails? Future<int> total() { return fetchPrice().then((price) => price + 5); }
Show answer
Future<int> total() async { final price = await fetchPrice(); return price + 5; }. If fetchPrice() fails, the await rethrows the error inside total, and since nothing catches it, total's returned Future completes with that same error. The caller sees it when it awaits total().