CodeBlanks Logo Icon CodeBlanks

Summary - Async basics

Combine async/await and Future.wait to write a parallel downloader.

Summary - Async basics

In this group you saw the fundamentals of asynchronous programming: asynchronous operations with Future, readable code with async/await, chaining with .then, error handling with Future.error and .catchError, parallel work with Future.wait. Now we combine them all in a parallel downloader example.

A parallel downloader fetches data from several sources at the same time. Each source is a Future; Future.wait starts them in parallel and collects the results in a list. On error you recover with .catchError or try/await/catch. This shows how asynchronous code is used in a real application.

Practice Your turn: download two sources in parallel

Write a function Future<String> fetch(String source) that returns Future.value("data-\$source"). In Future<void> main() async start fetch("a") and fetch("b") in parallel with Future.wait and print the result.

Starter code

main.dart
void main() {
  // Define fetch
  // call Future.wait in async main
  // print the result
}

Sample solution

main.dart
Future<String> fetch(String source) => Future.value("data-$source");

Future<void> main() async {
  final result = await Future.wait([fetch("a"), fetch("b")]);
  print(result);
}

Expected output

[data-a, data-b]

Practice Your turn: downloader with error catching

Write Future<String> fetch(String source) that returns Future.error(Exception("failed")) when source is "err", else Future.value("data-\$source"). In Future<void> main() async wrap await Future.wait([fetch("a"), fetch("err")]) in try; print with catch (e). The parallel error is caught.

Starter code

main.dart
void main() {
  // Define fetch (returns error for "err")
  // async main with try + await Future.wait
  // catch prints the error
}

Sample solution

main.dart
Future<String> fetch(String source) =>
    source == "err" ? Future.error(Exception("failed")) : Future.value("data-$source");

Future<void> main() async {
  try {
    await Future.wait([fetch("a"), fetch("err")]);
  } catch (e) {
    print(e);
  }
}

Expected output

Exception: failed

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the async tools

Term Meaning
Future a value later
async/await readable waiting
.then chaining
Future.wait parallel work

2 How to fetch from multiple sources in parallel?

main.dart
final s = await Future.wait([
  fetch("a"),
  fetch("b"),
]);
  • Future.wait
  • for loop
  • .then chain
  • sequential await Correct answer

Explanation: Future.wait runs in parallel.

All lessons in Beginner