Completer and Future in dart?

IBRIT picture IBRIT · Dec 5, 2012 · Viewed 15.2k times · Source
Future readData() {
    var completer = new Completer();
    print("querying");
    pool.query('select p.id, p.name, p.age, t.name, t.species '
        'from people p '
        'left join pets t on t.owner_id = p.id').then((result) {
      print("got results");
      for (var row in result) {
        if (row[3] == null) {
          print("ID: ${row[0]}, Name: ${row[1]}, Age: ${row[2]}, No Pets");
        } else {
          print("ID: ${row[0]}, Name: ${row[1]}, Age: ${row[2]}, Pet Name: ${row[3]},     Pet Species ${row[4]}");
        }
      }
      completer.complete(null);
    });
    return completer.future;
  }

The above is an example code taken from github SQLJocky Connector

I would like someone to explain me if possible why is the function which has a completer object created outside the pool.query is then calling a function completer.complete(null).

In short I am not able to understand the part after print executes.

Note:Kindly if possible I would also like to know how is future and Completer used for practical purpose both for DB and non DB operations.

I have explored the following links: Google groups discussion on Future and Completer

and the api reference documentation which is as given below Completer api reference and Future api Reference

Answer

John Evans picture John Evans · Dec 5, 2012

The Future object that is returned by that method is, in a sense, connected to that completer object, which will complete at some point "in the future". The .complete() method is called on the Completer, which signals the future that it is complete. Here's a more simplified example:

Future<String> someFutureResult(){
   final c = new Completer();
   // complete will be called in 3 seconds by the timer.
   new Timer(3000, (_) => c.complete("you should see me second"));
   return c.future;
}

main(){
   someFutureResult().then((String result) => print('$result'));
   print("you should see me first");
}

Here's a link to a blog post which details other scenarios where futures are helpful