async<T> static method
Wraps a Future operation and handles errors and exceptions that may
occur during its execution.
The async method takes the following parameters:
future: TheFutureoperation 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 returnsnull.onEmpty: A callback to execute when the operation returns an emptyListorMap.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, theonTimeoutcallback 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);
}
}
}