Skip to content

Instantly share code, notes, and snippets.

@ilikerobots
Created June 21, 2016 06:36
Show Gist options
  • Save ilikerobots/716d6f8fc2edc604e671e513e2690efe to your computer and use it in GitHub Desktop.
Save ilikerobots/716d6f8fc2edc604e671e513e2690efe to your computer and use it in GitHub Desktop.
Basic examples of ways to utilize async functions in Dart
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"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment