timeout 抽象方法

Future<T> timeout(
  1. Duration timeLimit,
  2. {FutureOr<T> onTimeout(
      )?}
    )

    timeLimit 经过后停止等待此future。

    创建一个新的 超时future,其结果与这个future相同,即 源future,如果源future按时完成。

    如果源future在 timeLimit 过去之前没有完成,将执行 onTimeout 操作,并使用其结果(无论它返回还是抛出异常)作为超时future的结果。 onTimeout 函数必须返回一个 T 或一个 Future<T>。如果 onTimeout 返回一个future,则使用最终结果的 替代结果future 来完成超时future,即使源future在替代结果future之前完成。重要的是源future没有按时完成。

    如果省略了 onTimeout,超时会导致返回的future以 TimeoutException 完成。

    在任何情况下,源future仍然可以在稍后正常完成。只是它不会作为超时future的结果被使用,除非它在时间限制内完成。即使源future在 timeLimit 过后完成了一个错误,该错误也会被忽略,就像一个值结果会被忽略一样。

    示例

    void main() async {
      var result =
          await waitTask("completed").timeout(const Duration(seconds: 10));
      print(result); // Prints "completed" after 5 seconds.
    
      result = await waitTask("completed")
          .timeout(const Duration(seconds: 1), onTimeout: () => "timeout");
      print(result); // Prints "timeout" after 1 second.
    
      result = await waitTask("first").timeout(const Duration(seconds: 2),
          onTimeout: () => waitTask("second"));
      print(result); // Prints "second" after 7 seconds.
    
      try {
        await waitTask("completed").timeout(const Duration(seconds: 2));
      } on TimeoutException {
        print("throws"); // Prints "throws" after 2 seconds.
      }
    
      var printFuture = waitPrint();
      await printFuture.timeout(const Duration(seconds: 2), onTimeout: () {
        print("timeout"); // Prints "timeout" after 2 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.
    Future<String> waitTask(String string) async {
      await Future.delayed(const Duration(seconds: 5));
      return string;
    }
    
    /// 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()?});