Last active
March 20, 2021 10:38
-
-
Save ftvs/ff8617ecf0f40ea26c028c26531bc719 to your computer and use it in GitHub Desktop.
awaiting for multiple futures with different return types executing in parallel without Future.wait. https://dartpad.dev/ff8617ecf0f40ea26c028c26531bc719
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
futureTest(); | |
} | |
futureTest() async { | |
final watch = Stopwatch()..start(); | |
print("elapsed: ${watch.elapsedMilliseconds}"); | |
final futureInt = Future.delayed(Duration(seconds: 2), () => 1); | |
final futureString = Future<String>.delayed(Duration(seconds: 2), () => "laterz"); | |
final n = await futureInt; | |
final s = await futureString; | |
print('n $n s $s'); | |
print("elapsed: ${watch.elapsedMilliseconds}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The gist of it is that this approach is type safe. Future.wait requres Futures to return the same type, or it could be used as
Future.wait<dynamic>()
, which loses type safety.Using await directly on each future will cause them to run one after another instead. Setting them in variables starts the asynchronous execution, then using await on the variables allows retrieval of the results.