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.)

Intro

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.
button.on.click.add((e) {
  costlyQuery();
  expensiveWork();
  lengthyComputation();
  print("done!");
});

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:

 button.on.click.add((e) {
   costlyQuery(() {
     expensiveWork(() {
       lengthyComputation(() {
         print("done!");
       });
     });
   });
 });

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
    completer.complete(results);
  });

  // 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:


 button.on.click.add((e) {
   costlyQuery()
   .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
    completer.complete(results);
  }, (error) {
    completer.completeException(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:

 button.on.click.add((e) {
   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() {
  Future.wait([
    costlyQuery(),
    expensiveWork(),
    lengthyComputation()
  ]).then((values) => print(values));
  
  // prints [costly, expensive, length]
}

Summary

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!
9 comments

Popular posts from this blog

  • Sponsor:  Register today for  New Game, the conference for HTML5 game developers . Learn from Mozilla, Opera, Google, Spil, Bocoup, Mandreel, Subsonic, Gamesalad, EA, Zynga, and others at this intimate and technically rich conference. Join us for two days of content from developers building HTML5 games today. Nov 1-2, 2011 in San Francisco.  Register now ! This is the second article in a Box2D series, following the Box2D Orientation article. The Box2DWeb port of Box2D contains a nice example to show off the basics of integrating physics simulations into your web app. This post will provide a walkthrough of the example, explaining the high level concepts and code. First, let's see the example in action. The code for the above is open source and available on GitHub. It was adapted from Box2DWeb's example . Animating Before we look at Box2D, it's important to understand how the above simulation is animated. You might think setInterval or setTimeout is
  • In which I port a snazzy little JavaScript audio web app to Dart , discover a bug, and high-five type annotations. Here's what I learned. [As it says in the header of this blog, I'm a seasoned Dart developer. However, I certainly don't write Dart every day (I wish!). Don't interpret this post as "Hi, I'm new to Dart". Instead, interpret this post as "I'm applying what I've been documenting."] This post analyzes two versions of the same app, both the original (JavaScript) version and the Dart version. The original version is a proxy for any small JavaScript app, there's nothing particularly special about the original version, which is why it made for a good example. This post discusses the differences between the two implementations: file organization, dependencies and modules, shims, classes, type annotations, event handling, calling multiple methods, asynchronous programming, animation, and interop with JavaScript libraries. F
  • Angular and Polymer, sitting in a DOM tree, B-i-n-d-i-n-g. First comes components, Then comes elements, Then comes the interop with the node dot bind. Angular , a super heroic MVC framework, and Polymer , polyfills and enhancements for custom elements built on top of Web Components, can live harmoniously in the same app. This post shows you how to connect Angular-controlled components to Polymer-controlled elements via data binding. And we do it all in Dart . Angular and Polymer I get asked "Should I use Angular or Polymer?" a lot. My answer is, "Yes". That is, both libraries have distinct strengths, and you can use both in the same app. Polymer excels at creating encapsulated custom elements. You can use those custom elements in any web app or web page, regardless if that app is built with Angular, Ember, etc. Angular excels at application engineering, with dependency injection, end-to-end testability, routing, and services. Here are som