Dart by Example: Futures

  1. import 'dart:async';
  2. main() {
  3. // Passing a callback to then() will invoke
  4. // that callback when the future completes
  5. onReady.then((String status) {
  6. print(status);
  7. });
  8. // Futures can be chained:
  9. onReady
  10. .then(print)
  11. .then((_) => print('done!'));
  12. // Futures can throw errors:
  13. onReady.catchError(() {
  14. print('error!');
  15. });
  16. }
  17. Future get onReady {
  18. var dur = new Duration(seconds: 1);
  19. var oneSecond = new Future.delayed(dur);
  20. // then() returns a new future that completes
  21. // with the value of the callback.
  22. return oneSecond.then((_) {
  23. return 'loaded!';
  24. });
  25. }
  1. $ dart futures.dart
  2. loaded!
  3. loaded!
  4. done!

by @jryanio | source | license