fromAsync<R, T> static method

FutureResult<R> fromAsync<R, T>(
  1. Future<T> func(), {
  2. R onSuccess(
    1. T result
    )?,
  3. BaseError onError(
    1. Object exception,
    2. StackTrace stackTrace
    )?,
})

Constructs a Result from a Future. If the Future completes successfully, the Result is a success with the value of the Future. If the Future fails, the Result is an error with the error of the Future.

Implementation

static FutureResult<R> fromAsync<R, T>(
  Future<T> Function() func, {
  R Function(T result)? onSuccess,
  BaseError Function(Object exception, StackTrace stackTrace)? onError,
}) async {
  try {
    final result = await func();
    if (onSuccess != null) {
      return successResult(onSuccess(result));
    }
    return successResult(result.cast<R>());
  } catch (exception, stackTrace) {
    if (onError != null) {
      return errorResult(onError(exception, stackTrace));
    }
    return errorResult(BaseError.fromError(exception, stackTrace));
  }
}