collectAsync<T, E> static method

  1. @useResult
Future<Result<T, E>> collectAsync<T, E>(
  1. FutureOr<Result<T, E>> collector(
    1. U check<U>(
      1. Result<U, E> result
      )
    )
)

Encloses any number of operations, optionally returning early on Err.

See collect for a synchronous version of this function.

Examples

final collected = await Result.collectAsync<int, String>((check) async {
  // This passes the check and `first` gets the value `2`
  final first = check(await Future.value(const Ok(2)));

  // This fails the check and the error is returned from the collector
  final second = check(await Future.value(const Err<int, String>('error')));

  // This is never reached
  return Ok(first + second);
});

// prints "Err(error)"
print(collected);

Implementation

@useResult
static Future<Result<T, E>> collectAsync<T, E>(
  FutureOr<Result<T, E>> Function(U Function<U>(Result<U, E> result) check) collector,
) async {
  try {
    return await collector(<U>(result) {
      return switch (result) {
        Ok(:final value) => value,
        Err(:final error) => throw _CheckException<T, E>(Err(error))
      };
    });
  } on _CheckException<T, E> catch (error) {
    return error.err;
  }
}