typestar

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

  1. Future<String> is a value that will arrive; async enables await.
  2. await fetchForecast() reads like sync code.
  3. .then chains the same future without await.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Async, step 22 of 27 in Language basics.

← Previous Next →