Skip to content

Instantly share code, notes, and snippets.

@riscait
Created August 9, 2024 07:06
Show Gist options
  • Save riscait/6e92840d5cb5cd9aec6ba6fd213d8fce to your computer and use it in GitHub Desktop.
Save riscait/6e92840d5cb5cd9aec6ba6fd213d8fce to your computer and use it in GitHub Desktop.
Record.wait vs Future.wait
void main() async {
// can catch exeptions.
wait();
// cannot catch exeptions.
record();
}
Future<bool> someFuture() async {
Future.delayed(const Duration(seconds: 1));
return true;
}
Future<void> exceptionFuture() async {
Future.delayed(const Duration(seconds: 1));
throw Exception('exceptionFuture');
}
Future<void> record() async {
try {
final (r) = await (
someFuture(),
exceptionFuture(),
).wait;
print('Record: success $r');
} on Exception catch (e, _) {
print('Record: catch exception $e');
} on Error catch (e, _) {
print('Record: catch error $e');
}
}
Future<void> wait() async {
try {
late final bool r;
await Future.wait([
() async {
r = await someFuture();
}(),
exceptionFuture(),
]);
print('Future.wait: success $r');
} on Exception catch (e, _) {
print('Future.wait: catch $e');
}
}
@riscait
Copy link
Author

riscait commented Aug 11, 2024

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