Basic examples of using Futures in Dart
Find this at dartpad.dartlang.org/ab210bb6bfa5add329df104854838bce.
Basic examples of using Futures in Dart
Find this at dartpad.dartlang.org/ab210bb6bfa5add329df104854838bce.
| import "dart:async"; | |
| import "dart:math" as math; | |
| const asyncDelay = const Duration(seconds: 3); | |
| ///Asynchronous method that returns back a random int | |
| Future<num> getNumber(num max) { | |
| return new Future.delayed(asyncDelay, () => new math.Random().nextInt(max)); | |
| } | |
| ///Simple async that returns given obj after a delay | |
| Future delay(dynamic z) => new Future.delayed(asyncDelay, () => z); | |
| ///Simple method defined as closure | |
| num addToNumber(num x, num y) => x + y; | |
| main() async { | |
| print(" * Starting *"); | |
| num newNum; | |
| // Line below is invalid, can't assign a Future to a num | |
| //newNum = getNumber(4); | |
| //Stop continued execution until the Future completes | |
| newNum = await getNumber(10); | |
| print("Awaited async call completed with result |$newNum|"); | |
| Future<num> f; //Futures are plain old objects | |
| //Retreive the Future and continue execution | |
| f = getNumber(10); | |
| f.then( (y) => print("Future completed with $y") ); | |
| print("Async call 1 completed with result |$f|"); | |
| //Chaining futures | |
| f = getNumber(10); | |
| f.then( (m) => addToNumber(7, m)) | |
| .then( (m) => addToNumber(21, m)) | |
| .then( (y) => print("Future completed with $y") ); | |
| print("Async call 2 completed with result |$f|"); | |
| //Chaining futures #2 | |
| Function add100 = (num n) => 100 + n; //Functions can be plain old objects | |
| Function add1000 = (num n) => 1000 + n; //Functions can be plain old objects | |
| Function printAndReturn = (num n) { print(" -Num is $n"); return n;}; | |
| getNumber(4).then(printAndReturn) | |
| .then(add100) | |
| .then(printAndReturn) | |
| .then(delay) | |
| //.then(addToNumber) //error, mismatched Function type | |
| .then(add1000) | |
| .then(printAndReturn); | |
| print(" * Ending * "); | |
| } |