async/await
- Dart course
- Beginner
- Lesson 107/116
- 5 min
Learn async code with async and await.
async/await
With async and await you write asynchronous code as if it were synchronous. You mark a function as async; that means it returns a Future. Inside you use await to wait for a Future to complete; the result goes straight into a variable.
Example: Future<void> main() async { final v = await Future.value(42); print(v); }. Here await waits for the Future, then v becomes 42. Much more readable than a .then chain. Inside an async function you catch errors with try/catch; no need for .catchError.
Using await
await only works inside an async function. It waits for a Future to complete and returns its result. With final v = await Future.value(42); the variable v immediately becomes 42. During await the function does not block; the caller returns and other work runs.
To wait for several Futures in order you use a separate await for each. On error you write try { await f(); } catch (e) { ... }; if the Future ends with an error the catch runs. Since an async function itself returns a Future, the caller can also await it. This makes chained asynchronous calls read like flat text.
Practice Your turn: async main
Mark main as async. Wait for final v = await Future.value(7); and print v. With await you get the Future result directly.
Starter code
void main() {
// mark as async
// wait for the Future value and print
}Sample solution
Future<void> main() async {
final v = await Future.value(7);
print(v);
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The async keyword
Future<void> main() ____ {
final v = await Future.value(42);
print(v);
}
Future<void> main() async {
final v = await Future.value(42);
print(v);
}
Explanation: An async function carries asynchronous code.
2 In which kind of function can await be used?
Future<void> main() async {
final v = ____ Future.value(42);
}- async
- static
- main
- sync Correct answer
Explanation: await works only inside an async function.
3 Match async/await
| Term | Meaning |
|---|---|
async |
marks the function |
await |
waits the Future |
try/catch |
catches errors |
Future<void> |
async main return type |