Dart by Example: Async / Await

  1. import 'dart:async';
  2. const Duration delay = const Duration(milliseconds: 200);
  3. // This function doesn't use async / await; just the
  4. // standard Future API
  5. Future loadLastName(String firstName) {
  6. return new Future.delayed(delay).then((_) {
  7. return firstName + 'son';
  8. });
  9. }
  10. // Marking a function with 'async' will return a future
  11. // that completes with the returned value.
  12. // This function is equivalent to [loadLastName]
  13. Future loadLastName2(String firstName) async {
  14. await new Future.delayed(delay);
  15. return firstName + 'son';
  16. }
  17. main() async {
  18. // 'await' will suspend execution of the function until the
  19. // future completes:
  20. var gregsLastName = await loadLastName('greg');
  21. var stevesLastName = await loadLastName2('steve');
  22. print('greg $gregsLastName');
  23. print('steve $stevesLastName');
  24. }
  25.  
  1. $ dart async_await.dart
  2. greg gregson
  3. steve steveson

by @jryanio | source | license