Skip to content

Instantly share code, notes, and snippets.

@ftvs
Last active March 20, 2021 10:38
Show Gist options
  • Save ftvs/ff8617ecf0f40ea26c028c26531bc719 to your computer and use it in GitHub Desktop.
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
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}");
}
@ftvs
Copy link
Author

ftvs commented Feb 21, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment