TExcelTAD
Home › Dart › async & await

async & await

async and await let you write asynchronous code that reads like synchronous code. Under the hood it's still futures and the event loop, but the compiler turns your straight-line code into the callback chain for you.

The basics

  • Mark a function async. It now always returns a Future — return 5; in an async function returning Future<int> completes the future with 5.
  • Inside it, await someFuture pauses this function until the future completes, then gives you its value. Other work keeps running meanwhile.
dart · try it yourself
Future<String> fetchUserName(int id) async {
  await Future.delayed(Duration(milliseconds: 20)); // simulate network
  return id == 1 ? 'Lan' : 'Guest';
}

Future<int> fetchOrderCount(String user) async {
  await Future.delayed(Duration(milliseconds: 10));
  return user.length * 3;
}

Future<void> main() async {
  print('loading...');
  final name = await fetchUserName(1);
  final count = await fetchOrderCount(name);
  print('$name has $count orders');
}
loading...
Lan has 9 orders

Compare with the then version: fetchUserName(1).then((name) => fetchOrderCount(name).then((count) => print(...))). With await, variables stay in scope and the code reads top to bottom.

What happens at await

await gives control back to the event loop. Code after the call to an async function may run before the async function finishes:

dart · try it yourself
Future<void> brew() async {
  print('  brew: start');
  await Future.delayed(Duration(milliseconds: 10));
  print('  brew: coffee ready');
}

Future<void> main() async {
  print('A');
  final pending = brew(); // runs synchronously until its first await
  print('B');
  await pending;
  print('C');
}
A
  brew: start
B
  brew: coffee ready
C

An async function runs synchronously up to its first await, then returns an uncompleted future to its caller.

Sequential vs concurrent

Awaiting one by one runs operations sequentially. If they're independent, start them all first and await together:

dart · try it yourself
Future<int> slowSquare(int n) async {
  await Future.delayed(Duration(milliseconds: 50));
  return n * n;
}

Future<void> main() async {
  final sw = Stopwatch()..start();
  final a = await slowSquare(2);
  final b = await slowSquare(3);
  final c = await slowSquare(4);
  final sequentialMs = sw.elapsedMilliseconds;
  print('sequential: ${a + b + c}');

  sw.reset();
  final results = await Future.wait([slowSquare(2), slowSquare(3), slowSquare(4)]);
  final concurrentMs = sw.elapsedMilliseconds;
  print('concurrent: ${results.reduce((x, y) => x + y)}');

  final (x, y) = await (slowSquare(5), slowSquare(6)).wait; // Dart 3 record form
  print('record wait: $x, $y');

  print('concurrent faster: ${concurrentMs < sequentialMs}');
}
sequential: 29
concurrent: 29
record wait: 25, 36
concurrent faster: true

The sequential version takes about 150 ms, the concurrent one about 50 ms.

async loops and await for

You can await inside any loop. For a Stream, await for processes each event as it arrives:

dart · try it yourself
Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    await Future.delayed(Duration(milliseconds: 5));
    yield i;
  }
}

Future<void> main() async {
  final ids = [3, 1, 2];
  for (final id in ids) {
    final label = await Future.value('item-$id');
    print(label);
  }

  await for (final n in countdown(3)) {
    print('T-$n');
  }
  print('liftoff');
}
item-3
item-1
item-2
T-3
T-2
T-1
liftoff

Return types

Declaration Meaning
Future<int> f() async Eventually produces an int
Future<void> f() async Eventually completes, no useful value — callers can await it
void f() async "Fire and forget" — callers can't await it or catch its errors. Avoid except for event handlers.
FutureOr<T> Either a T or a Future<T> (from dart:async) — for APIs accepting both

Tip: Make main return Future<void> and mark it async whenever it awaits something. The program then waits for everything you await before exiting.

Test yourself

What does an async function that returns 42 actually return to its caller?

  1. 42
  2. A Future<int> that completes with 42
  3. A Stream<int>
  4. void

Until which point does an async function run synchronously when called?

  1. It never runs synchronously
  2. Until its first await
  3. Until it returns
  4. Until the next microtask

How do you run two independent async calls concurrently and get both results?

  1. await a(); await b();
  2. await Future.wait([a(), b()])
  3. a().then(b())
  4. async { a(); b(); }