Converting callbacks to Futures

suggest change

Dart has a robust async library, with Future, Stream, and more. However, sometimes you might run into an asynchronous API that uses callbacks instead of Futures. To bridge the gap between callbacks and Futures, Dart offers the Completer class. You can use a Completer to convert a callback into a Future.

Completers are great for bridging a callback-based API with a Future-based API. For example, suppose your database driver doesn’t use Futures, but you need to return a Future. Try this code:

// A good use of a Completer.

Future doStuff() {
  Completer completer = new Completer();
  runDatabaseQuery(sql, (results) {
    completer.complete(results);
  });
  return completer.future;
}

If you are using an API that already returns a Future, you do not need to use a Completer.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents