Mention late errors in Future.timeout doc

Add an example where the source future results in an error that is ignored, with
only the `TimeoutException` surfacing in a catch block.

Move some comments to the same line as the `print` call to match other
lines in the example code. Use doc comment syntax on functions in the
example code.

Change-Id: I5d3146ebe8f7edce303d76ff36822ced9b831c95
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/272960
Reviewed-by: Lasse Nielsen <lrn@google.com>
Commit-Queue: Nate Bosch <nbosch@google.com>
This commit is contained in:
Nate Bosch 2022-12-02 20:05:26 +00:00 committed by Commit Queue
parent b493cdfc1b
commit b64f84d695

View file

@ -905,6 +905,9 @@ abstract class Future<T> {
/// at a later time.
/// It just won't be used as the result of the timeout future
/// unless it completes within the time bound.
/// Even if the source future completes with an error,
/// if that error happens after [timeLimit] has passed,
/// the error is ignored, just like a value result would be.
///
/// Examples:
/// ```dart
@ -919,7 +922,7 @@ abstract class Future<T> {
///
/// result = await waitTask("first").timeout(const Duration(seconds: 2),
/// onTimeout: () => waitTask("second"));
/// // Prints "second" after 7 seconds.
/// print(result); // Prints "second" after 7 seconds.
///
/// try {
/// await waitTask("completed").timeout(const Duration(seconds: 2));
@ -929,24 +932,34 @@ abstract class Future<T> {
///
/// var printFuture = waitPrint();
/// await printFuture.timeout(const Duration(seconds: 2), onTimeout: () {
/// print("timeout");
/// print("timeout"); // Prints "timeout" after 2 seconds.
/// });
/// // Prints "timeout" after 2 seconds.
/// await printFuture;
/// // Prints "printed" after additional 3 seconds.
/// await printFuture; // Prints "printed" after additional 3 seconds.
///
/// try {
/// await waitThrow("error").timeout(const Duration(seconds: 2));
/// } on TimeoutException {
/// print("throws"); // Prints "throws" after 2 seconds.
/// }
/// // StateError is ignored
/// }
///
/// // Returns [string] after five seconds.
/// /// Returns [string] after five seconds.
/// Future<String> waitTask(String string) async {
/// await Future.delayed(const Duration(seconds: 5));
/// return string;
/// }
///
/// // Prints "printed" after five seconds.
/// /// Prints "printed" after five seconds.
/// Future<void> waitPrint() async {
/// await Future.delayed(const Duration(seconds: 5));
/// print("printed");
/// }
/// /// Throws a [StateError] with [message] after five seconds.
/// Future<void> waitThrow(String message) async {
/// await Future.delayed(const Duration(seconds: 5));
/// throw Exception(message);
/// }
/// ```
Future<T> timeout(Duration timeLimit, {FutureOr<T> onTimeout()?});
}