Friday, March 9, 2012

Using Futures in Dart for Better Async Code

(Updated on March 9th, 2015.)

Dart bundles lots of functionality into its standard libraries, helping developers avoid reinventing the wheel from project to project. One of those wheels is a better way to handle asynchronous callback driven programs. Thanks to the Future class, potentially hard to follow callback code can be replaced with a more structured design.

(This is part 13 of an ongoing series about Dart.)


Let's pretend I have a set of potentially expensive methods that should be executed in order. Ideally, I should be able to write code like:

// Yikes! This will lock the page by running too
// many long processes in the main UI thread. {

Unfortunately, code like the above locks the main thread, freezing the application. Bummer.

Using callbacks is a typical way to make my UI responsive and move expensive processes off the initial handler. So I refactor the code into: {
   costlyQuery(() {
     expensiveWork(() {
       lengthyComputation(() {

The method signatures now look like:

void costlyQuery(onComplete());
void expensiveWork(onComplete());
void lengthyComputation(onComplete());

With all the nesting, though, things get a little confusing, and doesn't scale with a big algorithm. Imagine nesting these callbacks to 5 or 6 levels. Yikes.

Future is the future

The Future interface is designed to help design code that is more linear in appearance, without sacrificing the benefits of asynchronous behavior.

A Future represents a value that will be provided sometime in the future. The Future is a token that your method can return immediately, before the method performs its expensive calculations. Once the expensive work is done, the value can be given to the Future, thus notifying the consumer that the work is done.

Generally, the workflow when using a Future looks like:

  1. Enter the method.
  2. Construct a Future.
  3. Return the Future (before the expensive work even starts).
  4. At some point later, the event loop reaches the expensive work to be done.
  5. Expensive work is finished, gives resulting value to Future.
  6. The consumer of the Future is notified the value is present.
Refactoring to use a Future, the method signature becomes:

// return a Future immediately, then get to work
Future expensiveWork();

When using APIs that are not Future-based, it's often very helpful to also use a Completer. The Completer makes it easy to create and signal when a Future is complete. Only use a Completer when the asynchronous API that you're interacting with is not using Futures.

The implementation of expensiveWork() would look like:

Future<Results> costlyQuery() {
  var completer = new Completer();

  database.query("SELECT * FROM giant_table", (results) {
    // when complete

  // this returns essentially immediately,
  // before query is finished
  return completer.future; 

A client who calls costlyQuery() will immediately receive a Future in response. The client is notified when a value exists when the then() method is called on futureResults.

Future<Results> futureResults = costlyQuery();
futureResults.then((results) => renderTable(results));

Or, if you want to streamline the code:

costlyQuery().then((results) => renderTable(results));

I really like how the code reads. "Run a costly query, then, render the table."

Chaining futures

The real power of Futures comes in when you need to run multiple async methods in order, as our initial example illustrates.

Luckily, the Future interface provides a chain() method to make this easy. Assuming each of our expensive methods returns a Future, behold the glory: {
   .then((value) => expensiveWork())
   .then((value) => lengthyComputation())
   .then((value) => print("done!"));

Error handling

Futures pass along both values and exceptions. Here's the code for handling an exception and giving it to a Future.

  database.query("SELECT * FROM giant_table", (results) {
    // when complete
  }, (error) {

You can use any object to represent an exception, which is why we are simply passing the error to the Future as an exception.

Here's how to handle any exception from any of the chain() methods: {
   Future result = costlyQuery();
   result.then((value) => expensiveWork())
         .then((value) => lengthyComputation())
         .then((value) => print("done!"))
         .catchError((exception) => print("doh!"));

(Note that an upcoming addition to the language, method chaining, will make this code a bit nicer.)

Many futures

The Future class helps with handling multiple Future objects, if the order in which they are run doesn't matter. For example, you can kick off many Future instances and wait for all of them to finish with this code:

costlyQuery() {
  return new Future.value("costly");

expensiveWork() {
  return new Future.value("expensive");

lengthyComputation() {
  return new Future.value("lengthy");

void main() {
  ]).then((values) => print(values));
  // prints [costly, expensive, length]


Dart's Future interface represents a value that is provided sometime in the future. It can be returned immediately from a long running method, and it will signal the receiver when a value is ready.

Using a Completer to help manage a Future is a good idea. If you can run multiple Future objects in any order, consider using the Future.wait.

Next Steps

Read the previous Part 12 on Classes in DartRead more of my Dart poststry Dart in your browserbrowse the API docs, or file an issue request. Dart is getting ready, please send us your feedback!
Post a Comment


I'm probably required to say that the views expressed in this blog are my own, and do not necessarily reflect those of my employer. Also, except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the BSD License.