Photo by BENCE BOROS / Unsplash

Executing Asynchronous Functions in Dart in Parallel and Waiting for Them to Finish

Tech Stuff Feb 18, 2023

This blog is for a challenge that I've encountered while working on a flutter project. I was trying to execute multiple asynchronous functions in parallel. In my application, I had several time-consuming tasks that needed to be performed asynchronously, but I also needed to wait for all of them to finish before proceeding with the main application logic. While asynchronous programming is a powerful technique in Dart, I found myself struggling to balance the benefits of parallel execution with the need for sequential code execution.

Interestingly, Dart provides a straightforward solution to this problem with its Future.wait function. By creating a Future object for each asynchronous function and passing them into Future.wait, I was able to execute all of the functions concurrently and wait for them to complete before continuing with the main application logic. This allowed me to take full advantage of the benefits of asynchronous programming without having to sacrifice the simplicity of sequential code execution.

Here's an example of how to accomplish this in Dart, which may also be helpful for those who require it:

import 'dart:async';

void main() async {
  var firstResult = firstAsyncFunction();
  var secondResult = secondAsyncFunction();

  // Execute both fns parallelly and wait for them to finish 
  await Future.wait([firstResult, secondResult]);
  print("Done With them");
}

Future<void> firstAsyncFunction() async {
  print("Starting first async function");
  await Future.delayed(Duration(seconds: 2));
  print("First function completed.");
}

Future<void> secondAsyncFunction() async {
  print("Starting second async function");
  await Future.delayed(Duration(seconds: 3));
  print("Second function completed.");
}

✌️

Tags

Meron Hayle

Hi there, I'm Meron, a software engineer, an entrepreneur, and an artist, also known as a ninja in the art world.