async/await
- Dart course
- Intermediate
- Lesson 59/116
- 5 min
Learn async code with async and await.
async and await
async and await are the way to write asynchronous code with a synchronous look. async marks a function; await waits for a Future to complete.
When you add async to a function its return type becomes a Future. You make main async by writing void main() async. Inside an async function you can use await.
Example: void main() async { print('Started'); await Future.value(); print('Done'); }. Output: Started, Done. await pauses at that line, then continues.
Ordered output
When async and await are used together the code reads top to bottom. At the await line it waits, then moves to the next line. This looks synchronous but runs asynchronously.
Example: print('Started'); await Future.value(); print('Done');. The output is always 'Started' then 'Done'. await guarantees the order.
If you did not use await 'Done' might print immediately; the order would be unclear. await makes the order deterministic.
Practice Ordered async output
void main() async is already written. Start with print('Started'). Wait with await Future.value(). Then finish with print('Done').
Starter code
void main() async {
// first print 'Started', then wait on a Future, last print 'Done'
}Sample solution
void main() async {
print('Started');
await Future.value();
print('Done');
}Expected output
Started Done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the await keyword do?
var r = await f;- It deletes the Future
- It creates a new Future
- It waits until the Future completes Correct answer
- It throws an error
Explanation: await waits until the Future completes and gives the result.
2 async main
void main() ____ {
print('Started');
await Future.value();
print('Done');
}
void main() async {
print('Started');
await Future.value();
print('Done');
}
Explanation: the async keyword makes main asynchronous.
3 Match the async/await parts
| Term | Meaning |
|---|---|
async |
Function marker |
await |
Waiting |
Future.value() |
Awaited Future |
print('Done') |
After waiting |