Futures and async/await in Dart
async marks the function; await pauses it, not the program.
// async marks the function; await pauses it without blocking the
// program's single thread.
Future<String> fetchForecast() async {
await Future.delayed(const Duration(milliseconds: 50));
return 'SW 12 kts, clearing';
}
Future<void> main() async {
print('Requesting forecast...');
final forecast = await fetchForecast();
print('Forecast: $forecast');
// Futures also chain without await.
await fetchForecast().then((f) => print('Again: $f'));
}
How it works
Future<String>is a value that will arrive;asyncenables await.await fetchForecast()reads like sync code..thenchains the same future without await.
Keywords and builtins used here
Stringasyncawaitconstfinalreturnvoid
The run, in numbers
- Lines
- 15
- Characters to type
- 447
- Tokens
- 87
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 75 seconds.
Step 1 of 3 in Async, step 22 of 27 in Language basics.