๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Async and Await

An async function can pause at an await until a Future completes. The await expression then gives the completed value.

Awaiting a returned value

fetchScore is async and returns 42. main awaits it and prints the value it receives.

Future<int> fetchScore() async {
  return 42;
}

Future<void> main() async {
  var score = await fetchScore();
  print(score);
}

Two awaits in sequence

The first await finishes before the second line runs. The two values print in program order.

Future<void> main() async {
  var first = await Future.value('alpha');
  print(first);
  var second = await Future.value('beta');
  print(second);
}

An async function awaiting another

outer awaits inner and doubles the value it receives. main awaits outer and prints 14.

Future<int> inner() async {
  return 7;
}

Future<int> outer() async {
  var value = await inner();
  return value * 2;
}

Future<void> main() async {
  var result = await outer();
  print(result);
}

Results in input order

The microtask future finishes before the event future. Future.wait still lists the results in input order.

Future<void> main() async {
  var slow = Future(() => 'late');
  var fast = Future.microtask(() => 'early');
  var results = await Future.wait([slow, fast]);
  print(results);
}

A zero delay awaited

Future.delayed with Duration.zero completes on a later turn. The await pauses until that turn and then prints the value.

Future<void> main() async {
  var label = await Future.delayed(Duration.zero, () => 'ready');
  print(label);
}

Example

Future<int> loadCount() async {
  var base = await Future.value(4);
  return base + 1;
}

Future<void> main() async {
  var count = await loadCount();
  print('count $count');
  var pair = await Future.wait([Future.value('left'), Future.value('right')]);
  print(pair);
}

Key points

  • async marks a function that can pause at an await.
  • await pauses an async function until a Future completes.
  • After the pause, await gives the value the Future completed with.
  • An async function that returns a value completes its Future with that value.
  • Awaits written in sequence run in program order.
  • Future.wait takes a list of Futures and completes with a list of their values.
  • Future.wait keeps the results in the order of the input list.

In this example, loadCount awaits the value 4 and returns 5. main prints count 5 first. Future.wait then collects the two values in input order, and the print shows the list.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What order does Future.wait use for its result list?