Sub topic 6
Writing async functions with `await`
This chapter assumes basic Dart syntax, functions, variables, generic types such as List<int>, callbacks, and running a program with dart run. It also assumes that a Future<T> represents a result that will become available later.
An asynchronous function is a function marked with async. It returns a Future, even when its body appears to return an ordinary value. The await keyword reads the value inside a Future and pauses that function until the value is ready.
The pause does not block Dart's event loop. Other ready work can run while the asynchronous operation is in progress.
The working model
Consider this function:
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');
}fetchGreeting returns a Future<String>. The future completes with the string Hello after one second.
The main function is also asynchronous because it uses await. Its return type is Future<void>. When execution reaches await fetchGreeting(), Dart pauses main, but it does not freeze the program. After the future completes, Dart resumes main and assigns the completed value to greeting.
The output order is:
beforeHelloafter
The call to fetchGreeting starts before await pauses the current function. This is why await is useful for expressing a dependency: the next statement needs the result of the previous operation.
Reading asynchronous code
Without await, you work directly with a Future:
final Future<String> pendingGreeting = fetchGreeting();With await, you work with the eventual value:
final String greeting = await fetchGreeting();The second form does not make the operation synchronous. It changes how the rest of the current function is written. The function still yields control while waiting.
A useful sequence is:
await expressions can be combined with ordinary Dart expressions:
Future<int> loadCount() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return 7;
}
Future<String> describeCount() async {
final count = await loadCount();
return 'Count is $count';
}
Future<void> main() async {
print(await describeCount());
}loadCount first waits, then returns an integer. describeCount waits for that integer and builds a string. Each function exposes a Future to its caller while allowing its own body to read values directly.
Common mistakes
A frequent mistake is forgetting await:
Future<void> showCount() async {
final count = loadCount();
print(count); // Prints an Instance of 'Future<int>'
}Here, count is a Future<int>, not an int. Write final count = await loadCount(); when the value is needed.
Another mistake is starting an operation and never observing its result:
void saveWithoutWaiting() {
saveData(); // The caller cannot know whether it succeeded.
}If the caller must wait for completion, return the future:
Future<void> saveData() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
}
Future<void> saveAndReport() async {
await saveData();
print('saved');
}Use return await inside a try block when that block must catch an error from the returned future. A plain return saveData() can pass the future outward before the try block observes its failure.
Exercise
What is the type of result in final result = await fetchGreeting();, and what is the type of the expression fetchGreeting() before awaiting it?
Show answer
After awaiting, result is a String. Before awaiting, fetchGreeting() has type Future<String>.