Basic examples of ways to utilize async functions in Dart
Find this at dartpad.dartlang.org/716d6f8fc2edc604e671e513e2690efe.
Basic examples of ways to utilize async functions in Dart
Find this at dartpad.dartlang.org/716d6f8fc2edc604e671e513e2690efe.
import 'dart:async'; | |
import 'dart:math' as math; | |
var rnd = new math.Random(); | |
///Asynchronous method that returns back a random int | |
Future<int> getNumber(num max) { | |
return new Future.delayed(new Duration(seconds: rnd.nextInt(3)), () => rnd.nextInt(max)); | |
} | |
///Asynchronous method to flip a coin (without await) | |
Future<bool> isHeads() { | |
return getNumber(2).then( (int n) { | |
return n.isEven; | |
}); | |
} | |
///Asynchronous method to flip a coin (with wait) | |
Future<bool> isTails() async { | |
int n = await getNumber(2); | |
return n.isOdd; | |
} | |
///Asynchronous method to flip multiple coins (with Future.wait()) | |
Future<num> flipN(int n) { | |
List<Future> flips = new List<Future>(); | |
for (int i = 0; i < n; i++) { | |
flips.add(isHeads().whenComplete(() => print(" (flip completed)"))); | |
} | |
return Future.wait(flips).then((List results) { | |
return results.where((f) => f).length / results.length; | |
}); | |
} | |
main() { | |
for (int i = 0; i < 10; i++) { | |
isHeads().then( (f) => print ("Is Heads?: $f")); | |
isTails().then( (f) => print ("Is Tails?: $f")); | |
} | |
int numFlips = 10; | |
flipN(numFlips).then( (ratio) => print("${numFlips} flips completed with ${ratio} heads")); | |
} |