async<T> static method

Future<void> async<T>({
  1. required Future<T> future,
  2. OnTimeout? onTimeout,
  3. OnError? onError,
  4. OnWaiting? onWaiting,
  5. OnNull? onNull,
  6. OnEmpty? onEmpty,
  7. void onSuccess(
    1. T data
    )?,
  8. Duration timeout = const Duration(milliseconds: 10000),
})

Wraps a Future operation and handles errors and exceptions that may occur during its execution.

The async method takes the following parameters:

  • future: The Future operation to wrap.
  • onTimeout: A callback to execute when the operation exceeds a given timeout.
  • onError: A callback to execute when the operation throws an unhandled exception.
  • onWaiting: A callback to execute when the operation starts waiting.
  • onNull: A callback to execute when the operation returns null.
  • onEmpty: A callback to execute when the operation returns an empty List or Map.
  • onSuccess: A callback to execute when the operation completes successfully. The callback takes the operation's result as a parameter.
  • timeout: The maximum amount of time to wait for the operation to complete. If the operation takes longer than this amount of time, the onTimeout callback is executed.

Implementation

static Future<void> async<T>({
  /// The asynchronous operation to be executed.
  required Future<T> future,

  /// Callback function to be executed when the operation times out.
  OnTimeout onTimeout,

  /// Callback function to be executed when an error occurs during the execution of the operation.
  OnError onError,

  /// Callback function to be executed while the operation is waiting to complete.
  OnWaiting onWaiting,

  /// Callback function to be executed when the operation returns null.
  OnNull onNull,

  /// Callback function to be executed when the operation returns an empty list or map.
  OnEmpty onEmpty,

  /// Callback function to be executed when the operation is successful.
  void Function(T data)? onSuccess,

  /// The amount of time to wait before timing out the operation.
  Duration timeout = const Duration(milliseconds: 10000),
}) async {
  try {
    onWaiting?.call();

    final result = await future.timeout(timeout);

    if (result is List) {
      onEmpty?.call();
    } else if (result is Map) {
      onEmpty?.call();
    } else if (result == null) {
      onNull?.call();
    } else {
      return onSuccess?.call(result);
    }
  } catch (e, s) {
    if (e is TimeoutException) {
      onTimeout?.call();
    } else {
      onError?.call(e, s);
    }
  }
}