Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 61 ยท Asynchronous Dart

Futures and async/await

Understand Dart Futures: async and await, then and catchError, error handling, running tasks in parallel with Future.wait, timeouts and common mistakes.

Some work takes time: reading a file, calling a server, waiting for a timer. If your program stopped and stared at the clock until each task finished, an app would freeze and a server could only help one person at a time. Dart solves this with futures. A Future<T> is an object that stands for a value of type T that will be available later, or an error if the work fails.

The async and await keywords let you write code that waits for futures but still reads from top to bottom. The Dart code here is read-only. The TypeScript stand-ins use Promise, which behaves almost exactly like Future, so every idea can be run.

A first future

A future is in one of three states: uncompleted (the work is still going), completed with a value, or completed with an error. You get one from many library calls, or you create one yourself:

DART
Future<int> slowDouble(int n) {
  return Future.delayed(const Duration(milliseconds: 200), () => n * 2);
}

void main() {
  print('asking...');
  slowDouble(21).then((result) {
    print('result: $result');       // runs about 200 ms later
  });
  print('main is done');            // prints BEFORE the result
}

The output order is asking..., main is done, result: 42. The call to slowDouble returns immediately with an uncompleted future; the callback in then is stored and runs once the value arrives. Nothing blocks.

async and await

Chains of then get hard to read. Marking a function async lets you use await, which pauses that function (not the whole program) until the future completes and gives you its value:

DART
Future<int> slowDouble(int n) =>
    Future.delayed(const Duration(milliseconds: 200), () => n * 2);

Future<void> main() async {
  print('asking...');
  int a = await slowDouble(21);
  int b = await slowDouble(a);
  print('a = $a, b = $b');          // a = 42, b = 84
}

Rules to remember:

  • An async function always returns a Future. If you write Future<int> f() async { return 5; }, the 5 is wrapped for you. For no value, use Future<void>.
  • await only works inside an async function (or in a top-level main marked async).
  • An async function runs synchronously until its first await. Only then does it hand control back to its caller.
sequenceDiagram
    participant M as main
    participant W as work()
    participant T as timer
    M->>W: call work()
    W->>W: prints "in work" (synchronous part)
    W->>T: await Future.delayed(...)
    W-->>M: returns an uncompleted Future
    M->>M: prints "after the call"
    T-->>W: delay finished
    W->>W: resumes after the await

An async function starts running at once, returns a Future when it reaches its first await, and resumes later.

TypeScript Order of execution with async and await (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Handling errors

A future that fails completes with an error. With await, you catch it with an ordinary try/catch:

DART
Future<String> fetchUser(int id) async {
  await Future.delayed(const Duration(milliseconds: 50));
  if (id <= 0) {
    throw ArgumentError('id must be positive');
  }
  return 'user$id';
}

Future<void> main() async {
  try {
    print(await fetchUser(7));      // user7
    print(await fetchUser(-1));     // throws
  } on ArgumentError catch (e) {
    print('bad argument: ${e.message}');
  } finally {
    print('always runs');
  }
}

The callback style has equivalents: .catchError((e) { ... }) handles a failure and .whenComplete(() { ... }) runs either way, like finally. With await, prefer try/catch; it is clearer and easier to get right. A future whose error nobody handles reports an unhandled asynchronous error, which stops many programs, so never leave a failing future unobserved. Details of try, on and catch are in Exceptions and Error Handling.

Running tasks in parallel

Two awaits in a row run one after the other. If the tasks do not depend on each other, start them first and wait together with Future.wait:

DART
Future<int> task(String name, int ms) async {
  await Future.delayed(Duration(milliseconds: ms));
  print('$name done');
  return ms;
}

Future<void> main() async {
  var watch = Stopwatch()..start();

  // One after the other: about 300 ms
  await task('a', 100);
  await task('b', 200);
  print('sequential: ${watch.elapsedMilliseconds} ms');

  watch.reset();

  // Together: about 200 ms (the longest one)
  List<int> results = await Future.wait([task('c', 100), task('d', 200)]);
  print('parallel: ${watch.elapsedMilliseconds} ms, results $results');

  // Dart 3: wait on a record of futures and keep each result's own type
  var (name, count) = await (Future.value('Ada'), Future.value(3)).wait;
  print('$name has $count');
}

Note the word parallel here means concurrent waiting: Dart runs your code on one thread (see The Event Loop), but while one task waits for a timer or a network reply, the others can make progress. Future.wait returns the results in the same order as the input list. If one future fails, Future.wait reports the first error (after waiting for the others, unless you pass eagerError: true). Future.any completes with whichever future finishes first.

TypeScript Sequential versus parallel waiting (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Timeouts, completers and other tools

A future that never completes would hang a program forever, so give network calls a limit with timeout:

DART
import 'dart:async';

Future<void> main() async {
  try {
    await Future.delayed(const Duration(seconds: 5))
        .timeout(const Duration(milliseconds: 300));
  } on TimeoutException catch (e) {
    print('too slow: ${e.duration}');          // too slow: 0:00:00.300000
  }

  // Or supply a fallback value instead of throwing:
  var value = await Future.delayed(const Duration(seconds: 5), () => 'late')
      .timeout(const Duration(milliseconds: 300), onTimeout: () => 'fallback');
  print(value);                                // fallback
}

A timeout stops waiting; it does not cancel the underlying work. Dart futures cannot be cancelled in general.

Other handy pieces:

  • Future.value(x) and Future.error(e) create already-completed futures, useful in tests.
  • Future.delayed(duration, [computation]) completes after a pause.
  • Completer<T> lets you create a future and complete it yourself later, from a callback-based API: completer.complete(value) or completer.completeError(e); read it as completer.future.
  • FutureOr<T> is a type meaning "either a T or a Future<T>", used where an API accepts both.
  • unawaited(future) from dart:async says "I know I am not awaiting this on purpose". Forgetting an await is such a common bug that the unawaited_futures lint exists.

Common mistakes

  1. Forgetting await. var user = fetchUser(1); gives you a Future<String>, not a String. The analyzer usually points this out when you use the value.
  2. Awaiting in a loop when the tasks are independent. Use Future.wait over ids.map(fetchUser).
  3. Making a function async for no reason. If it only returns another future, you can often return it directly.
  4. Doing heavy computing in an async function. async does not mean "on another thread". A long loop still blocks everything; use an isolate for that (see the Isolates lesson later in this chapter).
  5. Ignoring errors from futures started with then and no catchError.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an async function return?

    Every async function returns a Future. A returned value of type T is wrapped into Future<T>.
  2. 2. In what order is the output? print('A'); f(); print('C'); where Future<void> f() async { print('B'); await Future.delayed(Duration.zero); print('D'); }

    An async function runs synchronously up to its first await, so B prints before C. D prints later, after the delay.
  3. 3. How do you wait for three independent futures at the same time?

    Future.wait completes when all of them are done and returns a list of results in input order. Future.any would finish at the first one.
  4. 4. What happens to the slow task when .timeout(...) fires?

    timeout throws a TimeoutException (or uses onTimeout) for the waiting code, but the original future is not cancelled.

Summary

  • A Future<T> represents a value or error that arrives later; async functions always return one.
  • await pauses only the current function; the code before the first await runs synchronously.
  • Handle failures with try/catch around await, or with catchError and whenComplete.
  • Use Future.wait (or a record's .wait) to run independent tasks together.
  • timeout limits how long you wait; it does not cancel work. Completer bridges callback APIs.
  • Do not forget await, and do not use async to hide CPU-heavy work.

Next, handle many values over time with Streams.