Dart by Example: Futures

1. import 'dart:async';

3. main() {

5. // Passing a callback to then() will invoke
6. // that callback when the future completes
7. onReady.then((String status) {
8. print(status);
9. });

11. // Futures can be chained:
12. onReady
13. .then(print)
14. .then((_) => print('done!'));

16. // Futures can throw errors:
17. onReady.catchError(() {
18. print('error!');
19. });
20. }

22. Future get onReady {
23. var dur = new Duration(seconds: 1);
24. var oneSecond = new Future.delayed(dur);

26. // then() returns a new future that completes
27. // with the value of the callback.
28. return oneSecond.then((_) {
29. return 'loaded!';
30. });
31. }
1. $ dart futures.dart
2. loaded!
3. loaded!
4. done!

by @jryanio | source | license