CodeBlanks Logo Icon CodeBlanks

Summary - Async

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

Summary - Async

In this group we learned the basics of asynchronous programming: Future represents an async result; async/await writes code synchronously; .then/.catchError builds chains; Future.wait runs in parallel; Completer enables manual completion.

Together these tools form the foundation of async code in Dart. They are used for network requests, file reads, timers and similar operations. They manage long tasks without blocking the main thread.

Now let's do an exercise that uses two tools together: run two Futures in parallel with Future.wait and print their sum.

Practice Sum of parallel Futures

void main() async is already written. Create two Future.value (1 and 2). Run them in parallel with Future.wait and wait with await. Print the sum of the two elements of the result list; for example print('Total: ${results[0] + results[1]}').

Starter code

main.dart
void main() async {
  // create two Future.value, combine with Future.wait, print the result
}

Sample solution

main.dart
void main() async {
  var f1 = Future.value(1);
  var f2 = Future.value(2);
  var results = await Future.wait([f1, f2]);
  print('Total: ${results[0] + results[1]}');
}

Expected output

Total: 3

Questions and answers

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

1 Match the async concepts

Term Meaning
Future Async result
await Waiting
Future.wait Parallel wait
Completer Manual completion

2 What is used to run multiple Futures in parallel?

  • Completer
  • then
  • Future.wait Correct answer
  • await

Explanation: Future.wait runs multiple Futures in parallel.

All lessons in Intermediate